Polymorphism in C#

The word Polymorphism means having more then one form.

Polymorphism can be static or dynamic. In static polymorphism it is determined at compile time. In dynamic polymorphism it is decided at runtime.

Static Polymorphism/Function Overloading

It is compile time polymorphism because the compiler already knows what type of object it is linking to and waht type of method is to be called. So linking a method at compile time is also called early binding.

In this code method the name is the same but its parameters are different so it is called operator overloading.

using System;

namespace Polymorphism

{

    class calculation

    {

        public int add(int a, int b)

        {

            return (a + b);

        }

        public int add(int a, int b, int c)

        {

            return (a + b + c);

        }

    }

}

RunTime Polymorphism/Operator overrinding

It is runtime polymorphism because it is linked at runtime. So linking a method at runtime is also called late binding.

In this code method the name is the same and its parameters are also the same so it is called operator overriding.

In the base class the method is declared "virtual" and in the derived class we override the same method. The virtual keyword indicates the method can be overridden in any derived class.

During run time, method overriding can be done using the inheritance principle and using the "virtual" and "override" keywords.

using System; 

namespace employee 

{

    public string firstname = "FN";

    public string secondname = "SN";

    public virtual void printfullname()

    console.writeline(firstname + " " + lastname);

}

    

public class parttime employee : employee

{       

    public override void printfullname()

        console.writeline("firstname" + " lastname "" parttime");  

}

}        

public class fulltimeemployee : employee       

{       

    public override void printfullname()         

    {       

        console.writeline("firstname + " " lastname + " fullname");  

    }

public class temporaryemployee : employee        

    public override printfullname()       

    {          

        console.writeline("firstname + " " lastname + " temporary ");  

    }

}           

public class programme       

    public static void main()    

        employee[] emp = new employee[4];    

    emp [0] = new employee();    

    emp [1] = new parttimeemployee();    

    emp [2] = new fulltimeemployee();    

    emp [3] = new tomporarytime employee();    

    foreach(employee e in emp)         

{          

    e.printfullname();                 

}    

}

When the code above is compiled and executed, it produces the following result:

FN SN ,FN SN parttime  
FN SN fulltime,
FN SN temporary 


Similar Articles