Operator Overloading in C# with Examples

The concept of function overloading can also be applied to operators. Operator overload allows the same operator to perform multiple operations. When used for custom data types, it provides additional functionality to C # operators. One or both operands allow custom implementations of multiple operations belonging to a custom class. Only one set of operators can be overloaded from C# predefined operators.

Syntax:

access specifier  className  operator Operator_symbol(parameters)
{
    // Code
}

Example:

class newclass
{

	public int num;
	public newclass(int num1)
	{
		num = num1;
	}
	public static newclass operator +(newclass newclass)
	{
		newclass.num = +newclass.num;
		return newclass;
	}
	public void show()
	{
		Console.WriteLine(num);
	}
}
class EntryPoint
{
	static void Main(String[] args)
	{
		newclass newclass = new newclass(50);
		newclass = +newclass;
		newclass.show();
	}
}

Output:

50

Overloadable and Non-Overloadable Operators

Notation Description
+,-,!,~,++,–– these operators take only one operand and they can be overloaded
+, -, *, /, % These are binary operator and they can take be overloaded
==, !=, = These are comparison operator and they can be overloaded
&&, || These are conditional logical operators and they can be overloaded
+=, -+, *=, /=, %=, = These are assignment operator and they can be overloaded

Advantages of operator overload:

  • Operator congestion provides additional functionality for C # operators when used for custom data types.
  • You can think of an operator as an internal compiler function.

Example:

using System;
class newclass
{
    public string name;
    public int number;
    public static newclass operator +(newclass newclass1, newclass newclass2)
    {
        newclass newclass3 = new newclass();
        newclass3.name = newclass1.name + "  " + newclass2.name;
        return newclass3;
    }
}
class Program
{
    static void Main(string[] args)
    {
        newclass newclass1 = new newclass();
        newclass1.name = "shahzad";
        newclass newclass2 = new newclass();
        newclass2.name = "hussain";
        newclass newclass3 = new newclass();
        newclass3.name = newclass1.name + newclass2.name;
        Console.WriteLine(newclass3.name);
    }
}

Output:

shahzad hussain