Method overload and general parameter

I am reading this question and 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 List<T> and whoever implements ICollection<T> would choose the second method, while MyClass (MyClass is just some class that does not implement ICollection, of course) would select 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 would just write list1.MyReset() .

The goal is to maintain the ability to distinguish between ICollection<T> and other classes, but also not provide explicitly common parameters.

Reply to comment: I plan to add more overloads, so it's not just Yes-Collection and Not-Collection .

+4
source share
1 answer

C # does not use common constraints in its I / O algorithm.

However, this is not like you really need type constraints. You can simplify your code as follows:

 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!"); } 
+4
source

All Articles