Click here to Skip to main content
Click here to Skip to main content

Operator Overloading in C# .NET

By , 7 Apr 2011
Rate this:
Please Sign up or sign in to vote.

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

krdeepak123

India India
No Biography provided

Comments and Discussions

 
Generalmistake Pinmembern.podbielski12-Apr-11 8:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 7 Apr 2011
Article Copyright 2011 by krdeepak123
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid