Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload generic List's Add with extension method

Tags:

c#

generics

I would like to overload a generic list's Add method so I can use collection initializations like:

var x = new List<Tuple<string>> { { "1", "2" }, { "1", "2" } };

(Where Tuple is a simple custom implementation of a binary tuple.) However, I created an extension method, put a using directive in the cs file, and still get the "No overload for method 'Add' takes 2 arguments"-error.
Is it not possible to do (with an extension method)?

Extension method code:

namespace ExtensionMethods {
    public static class Extensions{
        public static void Add<T>(this List<Tuple<T>> self, T value1, T value2) {
            self.Add(new Tuple<T> { value1, value2 });
        }
    }
}
like image 804
Protector one Avatar asked Oct 11 '22 10:10

Protector one


2 Answers

It is not possible via extension methods. In order to make this syntax working you have to create your own collection class which will have void Add(T value1, T value2) signature.

P.S.: What you've done is not overload and there is no way to overload anything in existing class.

UPDATE: Looks like my first sentence should be: "It is not possible via extension methods in C#"

like image 66
Snowbear Avatar answered Oct 15 '22 10:10

Snowbear


In C# 6.0[0] Microsoft allows the use of extensions methods in collection initializers. hurray :)

And since this isn't a .NET Framework or CLR change, but a compiler change, this feature can be used with .NET 4.0.

So the following is now valid C# code. (Tested in Visual Studio 2015 RC)

class Program
{
    static void Main(string[] args)
    {
        var x = new List<Tuple<string,string>> { { "1", "2" }, { "1", "2" } };
    }
}
public static class Extensions
{
    public static void Add<T1,T2>(this List<Tuple<T1,T2>> self, T1 value1, T2 value2)
    {
        self.Add(Tuple.Create( value1, value2 ));
    }
}

C# 6 Features [0]

like image 25
JamesF Avatar answered Oct 15 '22 09:10

JamesF