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?
Is there any way I can make an extension method take priority over a generic method?
309 views Asked by AlphaModder At
1
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: