3

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?

Andy Mehalick
  • 993
  • 8
  • 19
  • @fubo You're right, typo is fixed. – Andy Mehalick Jul 12 '16 at 13:36
  • Is the `class` constraint necessary? If not, you could make the first extension non-generic and make `item` directly of type `ISomeInterface`. – René Vogt Jul 12 '16 at 13:39
  • The extension method part is irrelevant btw, but see [duplicate](http://stackoverflow.com/questions/26037469/overload-resolution-issue-for-generic-method-with-constraints). – CodeCaster Jul 12 '16 at 13:40
  • Or [Method overload resolution with regards to generics and IEnumerable](http://stackoverflow.com/questions/4910018/method-overload-resolution-with-regards-to-generics-and-ienumerable), and so on. – CodeCaster Jul 12 '16 at 13:41
  • 1
    @CodeCaster I agree, same issue as duplicate – Andy Mehalick Jul 12 '16 at 13:55

1 Answers1

2

This should do it

var items = new[]
{
    new SomeClass()
};

items.DoSomething<SomeClass>();

That's of course assuming items is SomeClass[] .

asibahi
  • 857
  • 8
  • 14