0

I'm trying to make a list be able to added to by plusing an item into it.

Target use of code I'm trying to make happen:

List<int> numbers = new List<int>();
numbers += 10;

What I've tried. "operator +" should overload + and "this IList" should extend generic IList.

public static IList<T> operator +<T>(this IList<T> list, T element)
{
    list.Add(element);
    return list;
}

It's not working however, red underlines everywhere over it in visual studios 2012. What am I doing wrong? Is this not possible? Why could this work for a standard class but not a generic class?

Joshua
  • 293
  • 4
  • 19
  • [Here](http://stackoverflow.com/questions/14020486/operator-overloading-with-generics?rq=1)'s a similar question that might help you. – diiN__________ Mar 30 '16 at 11:56

2 Answers2

5

Operators can only be overloaded in the definition of the class. You can't override them from outside by using extension methods.

Also, at least one of the parameters must be of the same type as the class.

So the best you can do is something like:

public class CustomList<T> : List<T>
{
    public static CustomList<T> operator +(CustomList<T> list, T element)
    {
        list.Add(element);
        return list;
    }
}

That you can then use like:

var list = new CustomList<int> { 1, 2 };

list += 3;

Console.WriteLine(string.Join(", ", list)); // Will print 1, 2, 3
Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
-2

The accepted answer above works better for the question asked, but in addition to that if someone needs to add two lists of any type and preserve the original lists. I should probably have posted this on a different topic, but doing search on "overloading + operator in c#" brings up this as top results. It may help someone hopefully.

void Main()
{
    List<string> str = new List<string> {"one", "two", "three"};
    List<string> obj = new List<string> {"four", "five", "six", "seven"};
    foreach ( string s in str + obj ) Console.Write(s + ", ");
}

public class List<T> : System.Collections.Generic.List<T> 
{

    public static List<T> operator +(List<T> L1, List<T> L2)
    {
        List<T> tmp = new List<T>() ;
        foreach ( T s in L1 ) tmp.Add(s);
        foreach ( T s in L2 ) tmp.Add(s);
        return tmp ; 
    }
}

//one, two, three, four, five, six, seven,
madgosht
  • 1
  • 1
  • if all you looking to use is the default generic list of .Net Library the code might help. Using a tmp list helps keep original lists intact – madgosht Feb 23 '17 at 19:36
  • Would you mind adding some context to your answer? Just posting code can be useful, but a detailed explanation about it helps others as well. – Aaron Feb 23 '17 at 20:00
  • 1
    Won't work with the example provided by the OP. Accepted answer does work as expected, however. – zanussi Feb 23 '17 at 20:03