Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Operator Overloading in C# .NET

0.00/5 (No votes)
7 Apr 2011 1  
This article gives an overview about operator overloading in .NET using C#

Operators

Operator overloading which is also known as overloading basically provides a way to define and use operators such as +, -, and / for user-defined classes or structs. It also allows us to define/redefine the way operators work with our classes and structs. In this way, this technique allows programmers to make their custom types look and feel like simple types such as int and string. It basically consists of nothing more than a method declared by the keyword operator and followed by an operator. There are mainly three types of overloadable operators called unary, binary, and conversion. But not all operators of each type can be overloaded. Let us cover each type of operator in more detail below.

Overloading Unary Operators

Unary operators are those which require only a single operand/parameter for the operation. The class or struct involved in the operation must contain the operator declaration and they include +, -, !, ~, ++, --, true, and false. While overloading unary operators, the following rules apply:

  • +, -, !, or ~ must take a parameter of the defining type and can return any type
  • ++ or - must take and return the defining type
  • true or false must take a parameter of the defining type and can return a bool

So in brief, the mechanism of giving a special meaning to a Standard C# operator with respect to a user defined data type such as classes or structures is known as OPERATOR OVERLOADING.

  • All C # binary operators can be overloaded. i.e., +, - , *, / , %,&,|, <<,>>.
  • All C# unary operators can be overloaded. i.e., +,_,!,++,--.
  • All relational operators can be overloaded , but only as pairs. i.e., = =, !=, <>, <=, >=

In simple terms, let us say if + is overloaded. If you want to find a + b:

  • If a,b are integers, the result will be sum of a and b and result is int.
  • If a,b are float, the result will be sum of a and b and result is float.
  • If a,b are two strings, the result will be concatenation of String a and String b and final result is string.

In this way, + is overloaded with different operations depending upon the data.

Source Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OperatorOverloading
{
    class Rectangle
    {
        static void Main(string[] args)
        {
            Rectangle objRect1 = new Rectangle(10);
            Rectangle objRect2 = new Rectangle(20);
            Rectangle objRect3 = objRect1 + objRect2; 	// Calls operator + 
						// (Rectangle,Rectangle)
            Console.WriteLine(objRect3);
            Console.WriteLine(objRect3 + 15); // Calls operator + 
					// (Rectangle,int) and then ToString()
            Console.WriteLine(objRect3 + 2.5);// Calls operator + 
					// (Rectangle,double) and then ToString()
            objRect3 = 10; // Calls operator Rectangle(int)
            Console.WriteLine(objRect3);
            Rectangle objRect4 = 10;
            Console.WriteLine(objRect1 == objRect4); //Calls == operator
            Console.WriteLine(objRect1 != objRect4); //Calls != operator
            Console.WriteLine(objRect1 > objRect2); //Calls > operator
            Console.WriteLine(objRect1 <= objRect4); //Calls <= operator
        }

        private double Side;
        
        //public Constructor if int is passed convert to double and assign to Side
        public Rectangle(int objRect)
        {
        Console.WriteLine("Int->Double->Assign to Side");
        Side=(double)objRect;
        } 
        //OverLoaded constructor with double argument
        public Rectangle(double objRect)
        {
        Console.WriteLine("Double->Assign to Side");
        Side = objRect;
        } 
        //override ToString() method of object class.
        public override string ToString()
        {
        Console.WriteLine("Override object class's string");
        return this.Side.ToString();
        } 
        //Overloading + operator to add 2 Rectangle objects 
        //and return new Rectangle object
        public static Rectangle operator + (Rectangle x,Rectangle y)
        {
        Console.WriteLine("Overloading + with Rectangle,Rectangle");
        return new Rectangle(x.Side+y.Side);
        Console.WriteLine("");
        } 
        //Overloading + operator to add Rectangle objects with double side and 
        //return new Rectangle object
        public static Rectangle operator + (Rectangle x,double y)
        {
        Console.WriteLine("Overloading + with Rectangle,double");
        return new Rectangle(x.Side+y);
        } 
        
        //Overloading + operator to add Rectangle objects with int side 
        //and return new Rectangle object
        public static Rectangle operator + (Rectangle x,int y)
        {
        Console.WriteLine("Overloading + with Rectangle,int");
        return x +(double)y;
        } 

        public static implicit operator Rectangle(double s)
        {
        Console.WriteLine("Overloading = for Rectangle objRect5=1.5 assignment");
        return new Rectangle(s);
        } 
        
        public static implicit operator Rectangle(int s)
        {
        Console.WriteLine("Overloading = for Rectangle objRect5=10 assignment");
        return new Rectangle((double)s);
        } 
        
        //OverLoading == operator
        public static bool operator ==(Rectangle x,Rectangle y)
        {
        Console.WriteLine("Overloading == with Rectangle,Rectangle");
        return x.Side==y.Side;
        }
        
        //OverLoading != operator
        public static bool operator !=(Rectangle x,Rectangle y)
        {
        Console.WriteLine("Overloading != with Rectangle,Rectangle");
        return !(x==y); //This will call to operator == simple way to implement !=
        } 
        
        //Always override GetHashCode(),Equals when overloading ==
        public override bool Equals(object obj)
        {
        return this==(Rectangle)obj;
        } 
        
        public override int GetHashCode()
        {
        return (int)Side;
        } 
        
        //OverLoading > operator
        public static bool operator >(Rectangle x,Rectangle y)
        {
        Console.WriteLine("Overloading > with Rectangle,Rectangle");
        return x.Side>y.Side;
        } 
        
        //OverLoading < operator
        public static bool operator <(Rectangle x,Rectangle y)
        {
        Console.WriteLine("Overloading < with Rectangle,Rectangle");
        return x.Side<y.side; <="operator" (x="=y);" />= operator
        public static bool operator >=(Rectangle x,Rectangle y)
        {
        Console.WriteLine("Overloading >= with Rectangle,Rectangle");
        return (x>y) || (x==y); //Calls to operator == and >
        } 
        
        //Readonly Property
        public double Area
        {
            get
            {
                return 2*Side;
            }
        } 
    }
}

History

  • 7th April, 2011: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here