MrProgram
MrProgram

Reputation: 5242

How to write over an operator?

class Test
{
    public int a { get; set; }
    public int b { get; set; }

    public Test(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public static int operator +(Test a)
    {
        int test = a.a*a.b;
        return test;
    }

    public void Testa()
    {
        Test t = new Test(5, 5);
        Console.WriteLine((t.a + t.b));
    }
}

When I call the Testa() method I want the result to be 5*5, but I'm not sure how to use this method above were I write over the + operator

Upvotes: 2

Views: 119

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503489

Your method overloads the unary + operator. So you can see it in action if you write:

Test t = new Test(5, 5);
Console.WriteLine(+t); // Prints 25

If you wanted to overload the binary + operator, you'd need to give two parameters. For example:

// I strongly suggest you don't use "a" and "b"
// as parameter names when they're already (bad) property names
public static int operator +(Test lhs, Test rhs)
{
    return lhs.a * rhs.b + lhs.b * rhs.a;    
}

Then use it as:

public static void Main()
{
    Test x = new Test(2, 3);
    Test y = new Test(4, 5);
    Console.WriteLine(x + y); // Prints 22 (2*5 + 3*4)
}

Upvotes: 7

Servy
Servy

Reputation: 203812

You can't do that. The + operator overloads for integers are a part of the C# language specs, and cannot be overridden by user code.

What you could do is the following:

public class Test
{
    public int a { get; set; }
    public int b { get; set; }

    public Test(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public static Test operator +(Test first, Test second)
    {
        return new Test(first.a * second.a
            , first.b * second.b);
    }

    public override string ToString()
    {
        return a.ToString() + " " + b.ToString();
    }

    public void Testa()
    {
        Test t = new Test(5, 5);
        Test t2 = new Test(2, 6);
        Console.WriteLine(t + t2);
    }
}

The idea here is that you're overloading the operator for a Test class, not an int.

In your case you were actually overloading the unary plus operator, not the binary operator.

Upvotes: 1

Related Questions