c# – Operators overloading in other classes – Education Career Blog

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)
    {
        ...
    }
}

,

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.

,

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.

,

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? 🙂

Leave a Comment