I have two extension methods for an interface, one that performs an action on an instance of a class implementing the interface and one on a collection of classes implementing the interface. The problem is that the compiler always uses the first extension method and this creates a compile error, so I cannot use the collection version.
public interface ISomeInterface
{
}
public class SomeClass : ISomeInterface
{
}
public static class SomeClassExtensions
{
public static T DoSomething<T>(this T item) where T : class, ISomeInterface
{
return item;
}
public static IEnumerable<T> DoSomething<T>(this IEnumerable<T> items) where T : class, ISomeInterface
{
return items;
}
}
internal class Program
{
private static void Main()
{
var items = new[]
{
new SomeClass()
};
items.DoSomething(); // compiler error
}
}
The error is clear that the compiler is trying to use the first extension method:
The type 'ConsoleApplication1.SomeClass[]' cannot be used as type parameter 'T' in the generic type or method 'SomeClassExtensions.DoSomething(T)'. There is no implicit reference conversion from 'ConsoleApplication1.SomeClass[]' to 'ConsoleApplication1.ISomeInterface'.
Clearly I can rename one of the two extension methods but that's a last resort as this is for an open source project and I'm trying to avoid deviating from an established set of naming conventions.
I'm out of ideas on how to force what I need to work, perhaps there's a way to add to or adjust the generic type constraints?