Operator overloading in C#

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

This entry was posted in .Net, .Net 3.0 / 3.5 and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>