class Program
    {
        static void Main(string[] args)
        {
            Number n1 = new Number { X = 10 };
            Number n2 = new Number { X = 20 };
            Number n3 = n1 + n2;// +(n1,n2)
            Console.WriteLine("{0}+{1}={2}",n1.X,n2.X,n3.X);

            int result = n1 + 30;
            Console.WriteLine(result);
            Console.WriteLine(n1==n2);//False
            Console.WriteLine(n1 != n2); //True
        }
    }
}

class Number
{
    public int X { get; set; }
    public static Number operator +(Number n1, Number n2)
    {
        return   new Number { X = n1.X + n2.X };
    }
    public static int operator +(Number n1, int x)
    {
        return n1.X + x ;
    }
    public static bool operator ==(Number n1, Number n2)
    {
        return n1.X == n2.X;
    }
    public static bool operator !=(Number n1, Number n2)
    {
        return n1.X != n2.X;
    }

why is it good to use that way of writing code?

Recommended Answers

All 3 Replies

Because it makes it easier on others who want to use your code. For example, let us say you made a Matrix class. Which makes more sense to a developer:

Matrix A = new Matrix(4, 4);
Matrix B = new Matrix(4, 4);

Matrix C = A.MultiplyBy(B);   // This

Matrix D = A * B;    // or This?

Also, if you create objects and you want to be able to sort them, or compare them you'll need to overload the ==/!= operators.

Given that, it can be misused. For example, if you have a Car class, what would be the meaning of Car + Car Make sure when you are overloading operators that the meanings of things like +, -, /, * are obvious to someone looking at the code.

Of course your example looks to be one that just shows how to overload operators, not something that would be useful.

commented: Good explanation +8
commented: it is clear to me now +0
commented: An excellent explanation of the use of operator overloading :) +4

Exellect explanation.

I'd just like to add another angle to this:

Say you have properties in an object that, when added together, you'd like to add the individual properties. You can overload an operator and output an object that is the addition (or difference, or whatever) of the two objects you just used the operator on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.