Tuesday, July 19, 2011

C# and .NET interview questions - What is the difference between static polymorphism and dynamic polymorphism?

Static Polymorphism: - Static Polymorphism means “Compile” time polymorphism or “Early binding”.

Method Overloading is an example of Static Polymorphism, where method name is same with different parameters and implementation.

Example: -

Below is the simple code snippet for Method Overloading.

public class StaticPoly
{
public void Display(int x)
{
Console.WriteLine("Value of x:"+x);
}
public void Display(int x, int y)
{
int z = 0;
z = x + y;
Console.WriteLine("Addition of x and y is:"+ z);
}
static void Main(string[] args)
{
StaticPoly Obj = new StaticPoly();
Obj.Display(10);
Obj.Display(10,3);
Console.ReadLine();
}
}

In the above code snippet you can see that we have two methods with same name but with different parameters and implementation.
Dynamic polymorphism: - Dynamic polymorphism means “Runtime” time polymorphism or “Late binding”.

Method Overriding is an example of Dynamic Polymorphism, where the base class
method is overridden by override keyword and its implementation is also changed.


Example: -

Below is the simple code snippet for Method Overriding.

class A
{
public virtual void Display()
{
System.Console.WriteLine("Base Class A::Display");
}
}

class B : A
{
public override void Display()
{
System.Console.WriteLine("Derived Class B::Display");
}
}

class Demo
{
public static void Main()
{
A b;
b = new A();
b.Display();

b = new B();
b.Display();
Console.ReadLine();
}
}

In the above code snippet you can see that we have two methods with same name,
same signature but with different implementations.

View following one of most asked question on “What is Generics?”


See more videos on C# and Dotnet interview questions

Regards,

View authors more tutorials on Most asked c# interview questions









No comments: