Q & A on extension methods
and method invocation precedenceI got the following question about extension methods in email, and I thought it's of general interest, so I will answer it here:
When the CLR is looking at extension methods and the built in methods on a class – what is the order of precedence. Do you know?
Does it look at the extension methods first or the static methods that are on the class?
That's two questions, and I'll start with the second one. You can't call static methods declared on a type using the object.MethodName invocation syntax. The compiler will force you to use TypeName.MethodName to call a static method declared on a class. Furthermore, you can't declare extension methods inside the intended target type because extension methods must be declared inside a static class. The C# language rules do enforce some reasonable behavior on declaring and using extension methods, or any static method.
Now, let's get to the important question: who wins, extension mehods, or some other candidate method? The answer is in §26.2.3 of the C# Language Spec:
"...if the normal processing of the invocation finds no applicable instance methods (specifically, if the set of candidate methods for the invocation is empty), an attempt is made to process the construct as an extension method invocation..."
Paraphrasing, that means the following:
The compiler first looks for any suitable method (ignoring extension methods altogether). This search includes accessible methods declared on the type, and accessible methods declared on any of its base classes. It also includes any candidate generic methods declard on the type, and any of its base classes:
obj.MethodName( args );
obj.MethodName< TypeArgs >.( args );
If the set of candidate methods is empty, then the compiler will search any extension methods that are in scope.
The short version: extension methods always lose to other candidate methods when seeking the best invocation match.
Postscript: You can get yourself into strange situations if you declare multiple extension methods with similar signatures. But that'sthe topic of another post.