I have these Extension methods:
public static void Replace<T>(this IList list, T newItem)
public static void Replace<T>(this IList<T> list, IEnumerable newItems)
public static void Replace<T>( this IList<T> list, IEnumerable<T> newItems )
I have a Linq statement that produces an IList<IWell> called, wells. (I confirm at runtime that wells is IEnumerable<IWell>.)
However, the statement
SelectedValues.Replace( wells );
always hits the first extension method, not the second or third. (I confirm at runtime that SelectedValues is IList<IWell>.)
Is it obvious what I am doing wrong?
What is the declared type of
SelectedValuesand ofwells? Extension methods are bound at compile-time, not at runtime so it is the compile-time types that matter.Edit: Since you said that
SelectedValuesis declared as typeIList, the only possible candidate for use as an extension method onSelectedValuesof the three you provided isThe compiler then realizes that it can consider
wellsas aTwithTbeing the declared type ofwellsand then can invoke the methodwhere
SelectedValuesfills in for the parameterlistandwellsfills in for the parameternewItem, and the declared type ofwellsfills in for the type parameterT. This is why that extension method is invoked.Again, extension methods are bound at compile-time. If you want to invoke a different method, you need to use a different declared type for
SelectedValues.So, this is not a case of the compiler “Matching wrong Extension method,” this is a case of the compiler matching the only possible extension method. This behavior is by design; it is a feature, not a bug.