Long back one of my cousins Rajesh gives me an introduction to Operator overloading in C++, but at that time I was VB 6.0 guy and I didn’t give much importance to it. But yesterday I got a chance to work on some sample applications where I tried operator overloading on C#.
I overloaded the + operator for adding two persons objects, and here is the code.
//Person class.
public class Person
{
//Name of the Person
public string Name
{
get;
set;
}
//Operator overloading.
public static Person operator +(Person first, Person second)
{
//Returning person, by adding the Names.
return new Person()
{
Name = first.Name + " " + second.Name
};
}
}
And here is the void Main()
static void Main(string[] args)
{
Person firstPerson = new Person()
{
Name = "Person 1"
};
Person secondPerson = new Person()
{
Name = "Person 2"
};
//Adding Person objects
Person resultPerson = firstPerson + secondPerson;
//It will return Person 1 Person 2
Console.WriteLine(resultPerson.Name);
}
You can find Operator Overloading Tutorial in MSDN