23 - Operator Overloading in C#

23.1 Introduction Operator Overloading

Overloading can be applied to the operators in C#. Operator overloading provides the additional capabilities to C# operators when they are applied to user defined data types. The predefined set of C# operators can be overloaded.

The built – in types have a predefined operators associated with them. Consider an example of user defined data type int with the operators +, -, * and / provides support for mathematical operations. To make operations on a user – defined data type is difficult as the operations are built – in. To use operators with user defined data types, they need to be overloaded depending on the requirements.

An operator can be overloaded by defining a function to it. The function is declared using the operator keyword. Operators can be considered as functions to the compiler. A developer may overload the functions with similar signatures. Functions that specify the additional task for the operators are called operator functions.

For example, to overload the + operator, the following syntax is defined.

   <access specifier> class Name operator + ( parameters )
   {
    //Code to be executed
   }

 

The following code snippet is used to demonstrate the operator overloading.

class Distance
{
    public int Values;
    {
        get;
        set;
    }
    public static Distance operator + ( Distance d1, Distance d2 )
    {
        Distance d = new Distance();
        d.Values = d1.values + d2.values;
        return d;
    }
}
class Program
{
    static void Main ( string[ ] args )
    {
        Distance d1 = new Distance();
        Distance d2 = new Distance();
        d1.Values = 10;
        d1.Values = 20;
        Distance d3 = d1 + d2;    
        Console.WriteLine(“Sun is {0}”, d3.Values );
        Console.Read();
    }
}

The output for the code is as shown below:

In the above code, the + operator is overloaded to add the values in the objects of Distance class. The compiler interprets the statement d1+d2 as operator + (d1, d2), where the operator functions of the first operand is invoked with the second operand of the operator.

The following table describes the overloading ability of the operators in C#.

 

Operators

Description

+, -, !, ~, ++, --

These unary operators take one operand can be overloaded

+, -, *, /, %

These binary operators take two operands and can be overloaded

==, !=, <, >, <=, >=

The comparison operators can be overloaded

&&, ||

The conditional logical operators cannot be overloaded directly and evaluated by using the & and | which can be overloaded

+=, -=, *=, /==, %==

The assignment operators cannot be overloaded

=, ? :, - >, new, sizeof, typeof

These operators cannot be overloaded

23.2 Overloading Unary Operators

Unary operators take a single operand. The examples of the unary operators are (++) increment and (--) decrement operators.

Unary operators can be classified as follows:

1) Simple prefix unary operators as + or – operators

2) Pre and post increment and decrement operators as ++ prefix increment operator

1) Simple Prefix Unary Operators

A simple prefix unary operator may be defined by the function that takes one parameter. The compiler interprets ‘-object1’ as follows:

operator – (object1);

The operator – () function can be associated with the class by creating a member function. The operator – () function can be provided an object of the class as its parameter. This creates an association of the class with the function.

The following code shows the overloading of – operator.

   

class Calculate
{
    public int number1, number2;
    public Calculate ( int no1, int no2)
    {
        number1 = no1;
        number2 = no2;
    }
    public Calculate()
    {
    }
    public static Calculate operator – ( Calculate c1 )
    {
        c1.number1 = -c1.number1;
        c1.number2 = -c1.number2;
        return c1;
    }
    public void Print()
    {
        Console.WriteLine(“number1=” + number1);
        Console.WriteLine(“number2 =” + number2);
        Console.Read();
    }
    class Program
    {
        static void Main ( string[ ] args )
        {
            Calculate c = new Calculate(20, -40);
            c.Print();
            Calculate c1 = new Calculate();
            c1 = -c;
            c1.Print();
            Console.Read();
        }
    }
}

The output for the code is as shown below:

In the above code, the – operator is overloaded to make the variables of the class Calculate negative. In the statement, c1=-c, the – operator is used with the object of the Calculate class, which calls the operator overload method and makes the variable negative.

2) Pre and post increment and decrement operators

The increment operator increments the current value of an operand by 1 and returns the result. The decrement operator decrements the current value of an operand by 1 and returns the result.

While declaring the prefix and postfix notations and applying the notations, they must be public, static and unary. In C#, the single operator is sued for both prefix and postfix. The result of the postfix notation is the value of the operand before it is incremented or decremented. The following code snippet is used to explain the prefix notation.

    Watch w = new Watch ( 5 );
    Watch prefix = ++w;

 

The above statement will result in incrementing the value of a variable w and then assigning the value of w variable to the prefix object.

The result of the postfix notation is the value of the operand before it is incremented or decremented. The following code snippet

     Watch w = new Watch ( 5 );
     Watch postfix = w++;

 

The above statement will result the value of the operand before it is incremented or decremented.

The following code is an example of overloading the pre increment and post increment operators using structures.

struct Operoverload
{
    public int i;
    public Operoverload ( int initval)
    {
        this.i = initval;
    }
    public static Operoverload operator ++(Operoverload arg )
    {
        arg.i++;
        return arg;
    }
}
class Program
{
    static void Main ( string[ ] args )
    {
        Operoverload o1 = new Operoverload(1);
        Operoverload o2 = o1++;
        Console.WriteLine(o1.i);
        Console.WriteLine(o2.i);
        o2 = ++o1;
        Console.WriteLine(o1.i);
        Console.WriteLine(o2.i);
        Console.Read();
    }
}

The output for the code is as shown below:

23.3 Overloading Binary Operators

Binary operators work with two operands. The binary operators can be arithmetic operators, arithmetic assignment operators, and comparison operators. Overloading a binary operator is similar to overloading the unary operator, except that the binary operator requires an additional parameter.

User can overload simple binary operators. The following syntax shows the use of binary operator in C#.

    a <operator> b  

In the preceding syntax, <operator> is a symbol that denotes a binary operator. C# interprets the expression as:

   operator <operator> ( Object1, Object2 );

The following code snippet is used to demonstrate the simple binary operators.

class Data
{
    public int number;
    public Data()
    {
        number = 0;
    }
    public Data ( int n )
    {
        number = n;
    }
    public static Data operator + ( Data d1, Data d2 )
    {
        Data d3 = new Data();
        d3.number = d1.number + d2.number;
        return d3;
    }
    public void display()
    {
        Console.WriteLine ( “{0}”, number );
    }
}
class Program
{
    static void Main ( string[ ] args )
    {
        Data d = new Data ( 100 );
        Data d4 = new Data ( 200 );
        Data d5 = new Data (  );
        d5 = d + d4;
        d.display();
        d4.display();
        d5.display();
        Console.Read();
    }
}

The output for the code is as shown below:

In the above code, the + operator is overloaded to add the two objects of the Data class. The operator function receives one object as a parameter. In the code, d is an object of the Data class to which the object d4 is passed. When overloaded, the object to the left of the operator is a member and the object on the right is the operator is the parameter.

Like us on Facebook