Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods overload choice

I have two extension methods:

public static IPropertyAssertions<T> ShouldHave<T>(this T subject)
{
    return new PropertyAssertions<T>(subject);
}

public static IPropertyAssertions<T> ShouldHave<T>(this IEnumerable<T> subject)
{
    return new CollectionPropertyAssertions<T>(subject);
}

Now I write some code which uses it:

List<Customer> collection2 = new List<Customer>(); 
collection2.ShouldHave(); //first overload is chosen
IEnumerable<Customer> collection3 = new List<Customer>(); 
collection3.ShouldHave(); //second overload is chosen

Second overload is chosen only if I explicitly specify IEnumerable type. Is there any way to make second overload to be chosen in both cases?

like image 406
SiberianGuy Avatar asked Mar 25 '12 12:03

SiberianGuy


People also ask

Is it possible to override an extension method?

In addition to the existing answers, you can also "override" extension methods by altering the method signature: This can only be used of course if the target type is more specific than that of the existing extension method. Also, it might be necessary to do this for all applicable types.

What are the risks of using extension methods?

When using an extension method to extend a type whose source code you aren't in control of, you run the risk that a change in the implementation of the type will cause your extension method to break. If you do implement extension methods for a given type, remember the following points:

Should you implement extension methods for a given type?

If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level.

What are extension methods in C?

Extension Methods (C# Programming Guide) Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.


2 Answers

The first overload is a better match, because T is inferred as List<Customer>, which gives an exact match. For the second overload, it would infer T as Customer, so the parameter would be IEnumerable<Customer>, which is a less exact match than List<Customer>.

like image 129
Thomas Levesque Avatar answered Oct 11 '22 05:10

Thomas Levesque


Don't think so. Don't think it's possible that in this case IEnumerable<T> overload will be always called, as it has less accurate match in regard of T type. If you don't specify a concrete IEnumerable<T>, the best match will be always a first method, in this case.

like image 40
Tigran Avatar answered Oct 11 '22 07:10

Tigran