What is Operator Overloading in C#

First, we need to understand what is operator overloading. The operator overloading is a part of Polymorphism. Operator overloading means we need to prepare our operators (+, -, / etcetera) to perform some extra tasks that they are not programmed to do so.

operator-overloading

Operator Overloading

An operator is programmed to work with predefined data types. Now a plus (+) operator is programmed to add two numbers and concatenate two strings. This string concatenation is happening due to method overloading. The designer of C# programming language did operator overloading with (+) operator and said inside String class is + operator is being used to add two strings then concatenate those strings. This is an example of a predefined data type.

Let’s take an example of a custom data type called Karma. Just like the Karma we have in Reddit.

using System;

namespace Polymorphism
{
    class Karma
    {
        public int Value { get; set; }

        public static Karma operator +(Karma K1, Karma K2)
        {
            Karma K3 = new Karma();
            K3.Value = K1.Value + K2.Value;
            return K3;
        }

        public string GetKarma()
        {
            return string.Format("{0} Karma", Value);
        }

        public void AddKarma()
        {
            Value += 1;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Karma K1 = new Karma();
            Karma K2 = new Karma();
            K1.Value = 1;
            K2.Value = 2;

            Karma K3 = K1 + K2;
            K3.AddKarma();
            K3.AddKarma(); 
            
            Console.WriteLine(K3.GetKarma());
            
            Console.ReadLine();
        }
    }
}

The Answer to this program will be 5 Karma.

Related Posts

As you can see in the program above, we have creared a custom data type called Karma then we defined what is Karma. We defined there is an integer value to this Karma and then created a couple of methods to it like GetKarma and AddKarma.

GetKarma is programmed to give the value of Karma in a specific string format and AddKarma is programmed to add one value to the current value of Karma.

Finally, we did Operator Overloading where we told the + operator how to behave when being used with Karma. We told the operator whenever asked to add Two Karmas together, create the instance of those two Karmas and add their values together. The added value should be saved in the third instance of Karma and return the third Instance to the user.

This is just one example and operator overloading, we can do overload – (minus) opeartor, /(division) operator and others.

I hope the concept of operator overloading is clear in your mind now. Feel free to write any feedback in the comment box.

Till then stay safe stay healthy!