Operator Overloading in C#

Introduction

Polymorphism
Polymorphism is an concept of OOPS. Polymorphism in Latin word which describes 'poly' means many
'morphs' means forms.
We can divide the polymorphism into 2 types.
1. Static polymorphism (complied time)
2. Dynamic polymorphism (run time)

Static polymorphism
In this the binding is taken place in compile time. The different types of static polymorphism
are:-
a) Function Overloading
b) Operator Overloading
c) Constructor Overloading

Dynamic polymorphism
In this the binding that takes place at run-time. The difference types of dynamic polymorphism
are:-
a) Function Overriding
b) Abstract Class

Operator overloading
It is the concept of oops  as we know that in object-oriented concept each and every thing deals with classes and objects. Keyword class contains the definition of two operators  i.e. Assignment operator (=) and Ampersand (&) by default.We can perform the( +, -, *, /) on a string ,integer etc while talking with oops concept (C#) we cant directly perform (=,-,*,/)arithmetic operations between two objects. If we want to train ours class other than two operators than we need to do Operator Overloading .

Example of Operator Overloading

// FIND THE SUM OF TWO COMPLEX NO. BY OPERATOR OVERLOADING
using System;
public class ComplexNum
{
    public int real;
    public int imaginary;
    public ComplexNum(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }
    
// Syntax of Operator Overloading
  public static ComplexNum operator +(ComplexNum n1, ComplexNum n2)
    {
        return new ComplexNum(n1.real + n2.real, n1.imaginary + n2.imaginary);
    }
    // Override the ToString method to display an complex number in the suitable format:
    public override string ToString()
    {
        return (String.Format("{0} + {1}i", real, imaginary));
    }
    public static void Main()
    {
        ComplexNum cnum1 = new ComplexNum(4, 5);
        ComplexNum cnum2 = new ComplexNum(5, 6);
        // Add two Complex objects (num1 and num2) through the
        ComplexNum addition = cnum1 + cnum2;
        // Print the numbers
        Console.WriteLine("First complex number:  {0}", cnum1);
        Console.WriteLine("Second complex number: {0}", cnum2);
        Console.WriteLine("RESULT :The sum of the two numbers: {0}", addition);
        // Hault the output screen
        Console.Read();
    }
}

Output

op[ld.gif

Ebook Download
View all
Learn
View all