Thursday, May 19, 2016

Operator Overloading in C#

In today's post, I will be discussing operator overloading in C# with an example.

Operator Overloading

In general, operators like "+", "-", etc have pre-defined functionalities. They can be used for mathematical operations for add, subtract, etc. Using operator overloading, we can have our own implementations for operations where one or both the operands are of a user defined class or struct type.

Operator Overloading in C#

Many operators can be overloaded and some of the operators cannot be overloaded. And some of the operators can be overloaded only in pairs. Here is the table from MSDN that shows the complete list of operators that can be overloaded.

+, -, !, ~, ++, --, true, false
These unary operators can be overloaded.
+, -, *, /, %, &, |, ^, <<, >>
These binary operators can be overloaded.
==, !=, <, >, <=, >=
The comparison operators can be overloaded. However, they can be overloaded only in corresponding pairs.
&&, ||
The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded.
The array indexing operator cannot be overloaded, but you can define indexers.
The cast operator cannot be overloaded, but you can define new conversion operators.
+=, -=, *=, /=, %=, &=, |=, ^=, <<=,>>=
Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded.
=, ., ?:, ??, ->, =>, f(x), as, checked,unchecked, default, delegate, is, new,sizeof, typeof
These operators cannot be overloaded.

Let's take a look at an example of how operator overloading is done. Suppose, we have a Vector class and we want to overload the "+" operator. In order to overload any operator, we need to use "static" keyword and "operator" keyword like this:

public class Vector
    public int X { get; set; }
    public int Y { get; set; }

    public static Vector operator +(Vector A, Vector B)
       return new Vector() 
        { X = A.X + B.X, Y = A.Y + B.Y };


So now we can simply use "+" operator to add two vectors. So when we add two vectors, it adds their corresponding X and Y values and returns the new vector.

static void Main(string[] args)

       var vector1 = new Vector() { X = 2, Y = 3 };
       var vector2 = new Vector() { X = 4, Y = 5 };
       var vector3 = vector1 + vector2;
       Console.WriteLine("The new vector is: X = {0}, Y = {1}.", 
           vector3.X, vector3.Y);

The result is: The new vector is: X = 6, Y = 8.


We need to use operator overloading very carefully. It's easy to abuse it which can make the application hard to understand and maintain. If the operator overloading is not necessary to use and might make the code look bad, we should avoid it.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


1 comment: