जगदीश खोलिया: Polymorphism in C#.NET

Polymorphism in C#.NET

Polymorphism in C#.NET

According to MSDN, Through inheritance, a class can be used as more than one type; it can be used as its own type, any base types, or any interface type if it implements interfaces. This is called polymorphism.

In C#, every type is polymorphic. Types can be used as their own type or as a Object instance, because any type automatically treats Object as a base type.

Polymorphism means having more than one form. Overloading and overriding are used to implement polymorphism. Polymorphism is classified into compile time polymorphism or early binding or static binding and Runtime polymorphism or late binding or dynamic binding.

Compile time Polymorphism or Early Binding

The polymorphism in which compiler identifies which polymorphic form it has to execute at compile time it self is called as compile time polymorphism or early binding.

Advantage of early binding is execution will be fast. Because every thing about the method is known to compiler during compilation it self and disadvantage is lack of flexibility.

Examples of early binding are overloaded methods, overloaded operators and overridden methods that are called directly by using derived objects.
Example of Compile Time Polymorphism
Method Overloading- Method with same name but with different arguments is called method overloading.
- Method Overloading forms compile-time polymorphism.
- Example of Method Overloading:
class A1
void hello()
{ Console.WriteLine(“Hello”); }

void hello(string s)
{ Console.WriteLine(“Hello {0}”,s); }

Runtime Polymorphism or Late Binding

The polymorphism in which compiler identifies which polymorphic form to execute at runtime but not at compile time is called as runtime polymorphism or late binding.

Advantage of late binding is flexibility and disadvantage is execution will be slow as compiler has to get the information about the method to execute at runtime.

Example of late binding is overridden methods that are called using base class object.
Example of Run Time Polymorphism
Method Overriding- Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
- Method overriding forms Run-time polymorphism.
- Note: By default functions are not virtual in C# and so you need to write “virtual” explicitly. While by default in Java each function are virtual.
- Example of Method Overriding:
Class parent
virtual void hello()
{ Console.WriteLine(“Hello from Jagdish”); }

Class child : parent
override void hello()
{ Console.WriteLine(“Hello from Jagdish Kholiya”); }

static void main()
parent objParent = new child();
Hello from Jagdish Kholiya.