.Net application development specialists
asp.net, c#, vb.net, html, javascript, jquery, html, xhtml, css, oop, design patterns, sql server, mvc and much more
contact: admin@paxium.co.uk

Paxium is the company owned by myself, Dave Amour and used for providing IT contract development services including


  • Application development - Desktop, Web, Services - with Classic ASP, Asp.net WebForms, Asp.net MVC, Asp.net Core
  • Html, Css, JavaScript, jQuery, React, C#, SQL Server, Ado.net, Entity Framework, NHibernate, TDD, WebApi, GIT, IIS
  • Database schema design, implementation & ETL activities
  • Website design and hosting including email hosting
  • Training - typically one to one sessions
  • Reverse Engineering and documentation of undocumented systems
  • Code Reviews
  • Performance Tuning
  • Located in Cannock, Staffordshire
Rugeley Chess Club Buying Butler Cuckooland Katmaid Pet Sitting Services Roland Garros 60 60 Golf cement Technical Conformity Goofy MaggieBears Vacc Track Find Your Smart Phone eBate Taylors Poultry Services Lafarge Rebates System Codemasters Grid Game eBate DOFF

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.