Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 764
AlphaModder Avatar asked Sep 28 '22 12:09

AlphaModder


1 Answers

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.

like image 134
Bas Avatar answered Oct 01 '22 01:10

Bas