Oscar Sales Salvador
Oscar Sales Salvador

Reputation: 11

Defining arithmetic operations in a class

I'm creating a library dll in c# with my own classes. But, for arithmetic operations (+, -, *, /, ...) I've created methods like .Add (c1, c2) where c1 and c2 are objects of my class.

This method is great, but I'd prefer to be able to say: c3 = c1 + c2; and since I've already written my Add function, Multiply function, Divide function etc etc for my classes I'd like to define that:

c1 = c2 + c3 is the same that: c1 = MyClass.Add (c2, c3);

So I would reuse my code, if it's possible. I'm sure there is documentation and information about all of this in the web, but I can't find it, anything I search, Google looks to misunderstand my question.

How can I define basic arithmetic operations for objects of my classes?

Upvotes: 1

Views: 3042

Answers (1)

Selman Genç
Selman Genç

Reputation: 101701

You are looking for operator overloading.You need to overload + operator to tell the compiler how to perform an addition between two objects.Then you will be able to add two objects like you add two integer.

Here is an example of + operator overloading from msdn

public static Complex operator +(Complex c1, Complex c2) 
{
   return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}

Upvotes: 9

Related Questions