Author - Dave Amour

Dave Amour has used computers for as long as he can remember and intially started out as an IT trainer delivering a range of IT courses but for the last 11 years has been focusing on the arena of web application development. He was worked for numerous companies over the years and is currently working for Audacs Software Ltd. Dave is also a keen squash player and an active and sucessful member of Experts Exchange

Please feel free to submit any constructive comments which you can do at the bottom of this page.

Dave may be available for programming tuition or consultancy work. Contact via dave@audacs.co.uk
Dave Amour - Click to view CV 

Operator Overloading in C#

Within any programming language we have operators such as:

+   -   *   /

and many more.

So within C# we are well accustomed to seeing code like this:

int a = 2;
 
int b = 3;
 
Console.WriteLine(a + b);


One thing which C# gives us the option to do is to overload an operator.  What this means is we can make an operator, for example the + operator, behave differently if we use it with a specific class we have written.

So for example lets say we have a class Wibble then we could do this: 

Wibble a = new Wibble();
//Set some properties of a
 
Wibble b = new Wibble();
//Set some properties of b
 
Wibble c = a + b;


When we do overload an operator then we have to add a method to the class in question.  This leads to well encapsulated and cohesive code.  So lets have a look at a real example of this.  A really good real example would be Matrix addition (as in maths, not the film starring Keanu Reeves!) but this involves a bit of maths and while this is not too difficult I do not want to detract from the main purpose of this article so I am going to avoid that and use something which is simpler but also not really that useful.  What we shall do is constrcut a class to store an amount of money.  Now normally we would just use a standard numeric variable for this but doing it this way will give us a nice example.

So our class shall be called Money and it will initially look like this:

public class Money
{
    public int Pounds { get; set; }
    public int Pence { get; set; }
 
    public override string ToString()
    {
        return string.Format("{0} pounds and {1} pence", Pounds, Pence);
    }
}


So our class represents an amount of money by splitting up the pounds and pence into seperate public properties.  If we then needed to add two instances of our money class it would be a bit fiddly. We would have to add the pounds together and then add the pence together too but if the pence went over 100 then we would need to deal with that.  So this then gives us an ideal chance to overload the + operator so that we can use that to add two instances of our money class and the fiddly code will all be encapsulatd within the overloaded operator method within the Money class.

The first thing you need to do when overloading an operator is make the method both public and static.  The method should then return an appropriate type which for addition will just be another instance of the two classes you are adding.   You then put the word operator and then the actual operator you are overloading followed by a pair of brackets with the parameters in and for this example we would need two parameters of type Money which are the two instances we are trying to add together.

After that you just code the method as you would do any other method.  So our new and improved Money class now ends up looking like this:

public class Money
{
    public int Pounds { get; set; }
    public int Pence { get; set; }
 
    public static Money operator + (Money m1, Money m2)
    {
        int pounds = m1.Pounds + m2.Pounds;
        int pence = m1.Pence + m2.Pence;
 
        if (pence >= 100)
        {
            pounds += pence / 100;
 
            pence = pence % 100;
        }
 
        return new Money() { Pounds = pounds, Pence = pence };
    }
 
    public override string ToString()
    {
        return string.Format("{0} pounds and {1} pence", Pounds, Pence);
    }
}


We can then write a simple console app to test this with a few values as follows: 

class Program

{

    static void Main(string[] args)

    {

        Money m01 = new Money() { Pounds = 0, Pence = 0 };

        Money m02 = new Money() { Pounds = 0, Pence = 0 };

 

        Money m03 = new Money() { Pounds = 0, Pence = 50 };

        Money m04 = new Money() { Pounds = 0, Pence = 40 };

 

        Money m05 = new Money() { Pounds = 0, Pence = 50 };

        Money m06 = new Money() { Pounds = 0, Pence = 60 };

 

        Money m07 = new Money() { Pounds = 1, Pence = 0 };

        Money m08 = new Money() { Pounds = 0, Pence = 90 };

 

        Money m09 = new Money() { Pounds = 1, Pence = 20 };

        Money m10 = new Money() { Pounds = 2, Pence = 90 };

 

        Money m11 = m01 + m02;

        Money m12 = m03 + m04;

        Money m13 = m05 + m06;

        Money m14 = m07 + m08;

        Money m15 = m09 + m10;

 

        Console.WriteLine(m11);

        Console.WriteLine(m12);

        Console.WriteLine(m13);

        Console.WriteLine(m14);

        Console.WriteLine(m15);

 

        Console.Read();

    }

}


And that's about it other than to mention that this would be a great opportunity to look at unit testing but that's another story.

Any comments are always welcome.

Leave a comment

Name

Email (optional and not disclosed)



Email address is not disclosed but just used to alert you of new posts if entered
Word CV
HTML CV
PDF CV
Text CV
CMS Lite
ETraining
Planet Health
Florida Health
the Date Shack
Taylors
Emcat
Emtex
Browne Jacobson
Alliance & Leicester
Baird Leisure
Swarfega
Creature Comforts
Rugeley Chess Club
Katnip
Katmaid
Dudley NHS
Contact Me
Current Status