Operator Overloading in C#


C++ programmers enjoy a language feature that makes the program logical flow easier to read. Take for example if we try to add two integer variables.

int value1, value2;
int result;
result = value1 + value2;

Programmers are trained to read these statements in their sleep. Unfortunately, when dealing with non-standard types, it can be confusing reading statements like:

myClass.Salary = Employee.Calculate( myClass.Tax );

This is where overloading an operator comes in handy. Operator overloading allows a programmer to define the behavior of an operator on a particular type. For example, if you've defined your own class, you can have both classes use the (+) operator and you can write it as follows:

newClass = myClass + oldClass;

Overloading an operator is easy to do in C# and follows the same look and feel as C++. Therefore C++ users will feel very much at home here. The following is an example of overloading an operator:

public static myClass operator+ ( myClass left, myClass right );

A few things to remember is the keyword operator and followed by the operator itself. Hence if you want to overload the (-) operator, you would write the statement above as:

public static myClass operator- ( myClass left, myClass right );

The parameters left and right are the left and right side of the operator. Using our previous statement where we are calculating for newClass, left would be myClass and oldClass would be right. The following is a full listing example of how to implement operator overloading.

Listing 1
class myClass { private int myValue=0; public static myClass operator+ ( myClass left, myClass right ) { myClass tmpClass = new myClass();

tmpClass.value = left.value + right.value; return( tmpClass ); }

public void Display() { System.Console.WriteLine("myValue = {0}\n", myValue); }

public int value { set { myValue = value; } get { return (myValue); } } }

class Example { public static void Main() { myClass newClass; myClass oldClass = new myClass(); myClass dummy = new myClass();

dummy.value = 2; oldClass.value = 3;

newClass = dummy + oldClass; newClass.Display();

System.Console.WriteLine("newClass.value = {0}\n", newClass.value); } }



C# has a concept called pair operators. When you decided to overload the equal (==) operator, it is recommended that you also overload the not equal (!=) operator. The same goes for less than (<) and greater than (>); less than and equal to (<=) and greater than and equal to (>=). The reason for this requirement is because of the .Net platform. Other languages might be using the equal operator and might assume that the not equal to operator is also overloaded.

The copyright of the article Operator Overloading in C# in C# Programming is owned by Jose Aniceto. Permission to republish Operator Overloading in C# in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic