Is there any way I can make an extension method take priority over a generic method?

287 views Asked by At

In .NET, if there is a class with a method Foo<T>(T t) (no constraints) and a method Foo(string s), calling Foo("test") calls the Foo that accepts a string. This is all good and well, unless the string overload is an extension method, in which case the generic version is always called. Is there some workaround for this problem, or am I out of luck?

1

There are 1 answers

0
Bas On BEST ANSWER

Short answer: no

In page 163 of the C# 5.0 Language Specification, we can see that after all overload resolution was attempted on a Method Group (a set of overloaded methods), and no suitable candidates are found, the compiler will try to search for applicable extension methods. This means that all the funky stuff such as generic type inference will take precedence over extension methods. To quote:

If the resulting set of candidate methods is empty, then further processing along the following steps are abandoned, and instead an attempt is made to process the invocation as an extension method invocation (ยง7.6.5.2). If this fails, then no applicable methods exist, and a binding-time error occurs.