Marson Mao
Marson Mao

Reputation: 3035

Method overload and generic parameter

I read this question, and am trying to do something like:

static class ExtentionMethods
{
    static public void MyReset<T>(this T col)
    {
        Console.WriteLine("Not a collection!");
    }

    static public void MyReset<T, U>(this T col) where T : ICollection<U>
    {
        col.Clear();
        Console.WriteLine("Cleared!");
    }

    // and maybe more overload for T : IWhatevetInterface<U>
}

so that List<T> and whoever implement ICollection<T> would choose the second method, while MyClass (MyClass is just some class that not implementing ICollection, of course) would choose the first, for example:

List<int> list1 = new List<int>();
list1.MyReset<List<int>, int>(); // "Cleared!"
MyClass x = new MyClass(); 
x.MyReset(); // "Not a collection!"

It works fine, but the problem is, how can I avoid writing <List<int>, int> for list1.MyReset<List<int>, int>()? I'd like to simply writing list1.MyReset().

The goal is to sustain the ability to distinguish ICollection<T> and other classes, but also not to explicitly providing the generic parameters.

Responding to comment: I'm planning to add more overloads, so the case is not only Yes-Collection and Not-Collection.

Upvotes: 4

Views: 209

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103447

C# does not use generic constraints in its type-inference algorithm.

However, it doesn't look like you actually need type-constraints. You could simplify your code like this, which does work:

static public void MyReset(this object col)
{
    Console.WriteLine("Not a collection!");
}

static public void MyReset<T>(this ICollection<T> col)
{
    col.Clear();
    Console.WriteLine("Cleared!");
}

static public void MyReset<T>(this IWhateverYouLike<T> col)
{
    col.ClearItIfYouLike();
    Console.WriteLine("Cleared!");
}

Upvotes: 4

Related Questions