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?
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.
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:
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.
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.
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>
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With