4

Can I overload operators for class A in class B in C#? For example:

class A
{
}

class B
{
    public static A operator+(A x, A y)
    {
        ...
    }
}
Lavir the Whiolet
  • 1,006
  • 9
  • 18

3 Answers3

5

No; one of the parameters must be the containing type.

From section §10.10.2 of the language specification (version 4.0):

The following rules apply to binary operator declarations, where T denotes the instance type of the class or struct that contains the operator declaration:

• A binary non-shift operator must take two parameters, at least one of which must have type T or T?, and can return any type.

You should think about why. Here's one reason.

class A { }
class B { public static A operator+(A first, A second) { // ... } }
class C { public static A operator+(A first, A second) { // ... } }

A first;
A second;
A result = first + second; // which + ???

Here's another:

class A { public static int operator+(int first, int second) { // ... } } 

Assume this allowed for a moment.

int first = 17;
int second = 42;
int result = first + second;

Per the specification for operator overload resolution (§7.3.2), A.+ will have precedence over Int32.+. We've just redefined addition for ints! Nasty.

Community
  • 1
  • 1
jason
  • 236,483
  • 35
  • 423
  • 525
1

No, you can't. error CS0563: One of the parameters of a binary operator must be the containing type

"In each case, one parameter must be the same type as the class or struct that declares the operator" quote from Documentation on overloading operators.

Wesley Wiser
  • 9,491
  • 4
  • 50
  • 69
0

Generally saying NO, but you can do something like following, if it helps :)

class A
{
    public static A operator +(A x, A y)
    {
        A a = new A();
        Console.WriteLine("A+"); // say A
        return a;
    }
}

class B
{
    public static A operator +(A x, B y)
    {
        A a = new A();
        Console.WriteLine("return in:A,B in out:A in class B+"); // say B
        return a;
    }

    public static A operator +(B x, B y)
    {
        A a = new A();
        Console.WriteLine("return in:B,B in out:A in class B +");
        return a;
    }
    // and so on....

}


B b = new B();
A a = new A();
A a1 = new A();
B b1 = new B();

a = b + b1; // here you call operator of B, but return A
a = a + a1; // here you call operator of A and return A

To understand your problem, can i ask why you want to do that? :)

dmitril
  • 59
  • 1
  • 4
  • I want to extend IEnumerable with "+", "==" and "!=" operators. – Lavir the Whiolet Oct 21 '10 at 05:20
  • Then i think your class that you will enumirate should be derived from System.Collections.IEnumerable. And then in you class(that derives from IEnumerable) you have to overload operators you need and that should do the trick. – dmitril Oct 21 '10 at 06:34
  • I need to compare and concatenate any IEnumerables in fact, whether they are Lists or Sets or any other data structures. – Lavir the Whiolet Oct 22 '10 at 14:47