Operator Overloading in C#
One of the greatest things you can find in c# is operator overloading capability. This is very awesome and applicable especially in a calculation related solution. We all know what is the easiest way to add two numbers, or two strings, simply by using + operator. Short example:
int a = 5; int b = 3;
int c = a + b;
Console.WriteLine(c); //output here is [8]
string firstName = "Aleksandar", lastName = "Ilioski";
string fullName = firstName + " " + lastName;
Console.WriteLine(fullName); //output here is [Aleksandar Ilioski]
Isn’t it great? Depending from the type (int/string) we have a different behavior and we get the desired result.
Lets assume now that we have our custom type called “ComplexNumber”. As we all know this is a type of number that has real numbers and an imaginary unit. Often we represent these kind of numbers as a + bi (where a and b are real numbers and i is the imaginary unit). Feel free to check out Wikipedia for more details about these complex numbers.
The code below is showing a very simple implementation of our type “ComplexNumber”
public class ComplexNumber
{
public int A { get; set; }
public int B { get; set; }
//overload of the ToString method to be used for console printing our complex numbers
public override string ToString()
{
return A + " + " + B + "i";
}
}
Lets now try to add two complex numbers the same way we were adding int and string before.
static void Main()
{
ComplexNumber x, y, z;
x = new ComplexNumber();
y = new ComplexNumber();
x.A = 2;
x.B = 3;
y.A = 5;
y.B = 6;
z = x + y;
Console.WriteLine(z); //Compiler Error
}
Oh no, we get this Error: Operator ‘+’ cannot be applied to operands of type ‘OperatorOverload1337Admin.ComplexNumber’ and ‘OperatorOverload1337Admin.ComplexNumber’. What now? How can we add Complex numbers then? Well we can add static method to our ComplexNumber class that will handle the adding part for us. We can even call the method Add so its functionality is obvious from the name. (TIP: ALWAYS try to name your methods in an obvious manner. This will make life easier in the long run.)
public static ComplexNumber Add(ComplexNumber x, ComplexNumber y)
{
ComplexNumber rez = new ComplexNumber();
rez.A = x.A + y.A;
rez.B = x.B + y.B;
return rez;
}
Later we can use it with slight modification in our previous example like this:
static void Main()
{
ComplexNumber x, y, z;
x = new ComplexNumber();
y = new ComplexNumber();
x.A = 2;
x.B = 3;
y.A = 5;
y.B = 6;
z = ComplexNumber.Add(x, y);
Console.WriteLine(z); //No more error and the output is: [7 + 9i]
}
Wow great, it is finally working. We did it, didn’t we? Hm… What if we could do that using the first method z = x + y; it was so easy, natural, intuitive and no code changes at all. If only there was such way…
Well there is, of course there is, this is c# remember? That’s why I love it. It is called Operator overloading. Check out the example below:
public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y)
{
ComplexNumber rez = new ComplexNumber();
rez.A = x.A + y.A;
rez.B = x.B + y.B;
return rez;
}
This is just a simple method with just a few key things to remember.
- We do overload operators using the operator keyword followed by the symbol of the operator that need to be overloaded.
- The Method has to be public static
- The Methods return type has to be the same with the type where this method lives
- Methods have to have at least one parameter of the type in which this method is declared
Wasn’t this awesome?! This way you can overload almost all operators. Also another important thing is that when you overload + operator, += is overloaded automatically for you. Further more, now we can simplify our existing Add method like below:
public static ComplexNumber Add(ComplexNumber x, ComplexNumber y)
{
return x + y;
}
And of course, we can now enjoy Adding our complex number variables like we first wanted to z=x+y.
I hope this tutorial was useful and fun for all of you, as much as it was fun for me to write it. Please don’t forget to check other tutorials here on 1337Admin as well, and learn many new things. Last thing here is full code listing:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;
namespace OperatorOverload1337Admin
{
static class Program
{
static void Main()
{
ComplexNumber x, y, z;
x = new ComplexNumber();
y = new ComplexNumber();
x.A = 2;
x.B = 3;
y.A = 5;
y.B = 6;
z = x + y;
Console.WriteLine(z);
}
}
public class ComplexNumber
{
public int A { get; set; }
public int B { get; set; }
public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y)
{
ComplexNumber rez = new ComplexNumber();
rez.A = x.A + y.A;
rez.B = x.B + y.B;
return rez;
}
public static ComplexNumber Add(ComplexNumber x, ComplexNumber y)
{
return x + y;
}
//overload of the ToString method has to be used for console prating of our complex numbers.
public override string ToString()
{
return A + ” + ” + B + “i”;
}
}
}
This concludes the short tutorial on Operator Overloading in C#.