Operator Overloading

What is Operator overloading?

Opearator overloading is a concept which is related to polymorphisam. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined.

Operator overloading gives the ability to use the same operator to do various operations

Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list.

Let's try to understand  Operator overloading (+)  by below example. using the + Operator you can do addition of two values and also contact two strings as below

 Obj 1 Operator     Obj 2 Result
 "C#"+ "Tutorial" C# Tutorial  
 15   +     20 35
Obj1       +    Obj2  can we do like that?? (let's do that with Operator Overloading) 


Please see below example for operator overloading and get to know that how we do addition of Obj1 + Obj2. run it on your machine to get more clerify.

    class Proram
    {
        public static void Main()
        {
            Course obj1 = new Course();
            obj1.Name = "C#";
            obj1.TotalMarks = 200;

            Course obj2 = new Course();
            obj2.Name = "Programming";
            obj2.TotalMarks = 300;

            Course obj3 = new Course();
            obj3 = obj1 + obj2;//Here operator overloading called.

            Console.WriteLine(obj3.Name + " - " + obj3.TotalMarks);
            Console.ReadLine();
        }
    }
    class Course
    {
        public string Name = "";
        public int TotalMarks = 0;

        public static Course operator +(Course Obj1, Course Obj2)
        {
            Course Obj3 = new Course();
            Obj3.Name = Obj1.Name + Obj2.Name;
            Obj3.TotalMarks = Obj1.TotalMarks + Obj2.TotalMarks;
            return Obj3;
        }
    }

Output
C#Programming - 500




Please visit given link for more details on Operator overloadig 

1 comment:

Please let me know if you have any feedback or doubts.

Jagged Array

What is Jagged Array? Jagged array is called as "array of arrays". when you need a data inside your array element at that time you...