8

I'm trying to overload an operator in C# (don't ask why!) that applies to Lists. For example, I'd like to be able to write:

List<string> x = // some list of things
List<string> y = // some list of things
List<string> z = x + y

so that 'z' contains all the contents of 'x' followed by the contents of 'y'. I'm aware that there are already ways to combine two lists, I'm just trying to understand how operator overloading works with generic structures.

(This is the List class from Systems.Collections.Generic, by the way.)

Joe
  • 3,804
  • 7
  • 35
  • 55

1 Answers1

7

As far as I know, this is not doable: you must implement the operator overload in the type that uses it. Since List<T> is not your type, you cannot override operators in it.

However, you can derive your own type from List<string>, and override the operator inside your class.

class StringList : List<string> {
    public static StringList operator +(StringList lhs, StringList rhs) {
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    Don't forget that operators are chosen based on the compile-time types. So `List a = new StringList(), b = new StringList(); var c = a + b` wouldn't work. – svick Feb 04 '12 at 18:14
  • 1
    @svick You are absolutely right, it is not possible to trick the compiler into somehow accepting your operator on operands that are not *statically* typed as your class where you defined the operator. – Sergey Kalinichenko Feb 04 '12 at 18:17
  • So why can I overload `*` to work with `String`s, but not `List`s? – Joe Jan 27 '13 at 08:43
  • @Joe How do you override `*` to work with `String`s? [Eric Lippert from the C# compiler team says you cannot overload operators of `String`s](http://stackoverflow.com/a/2587897/335858). Could you provide some code? This may be worth its own question. – Sergey Kalinichenko Jan 27 '13 at 12:15