Wednesday, November 7, 2012

Static polymorphism and dynamic keyword in C#

Static Polymorphism - is kind of polymorphism also known as function overloading(or operator overloading).

Static polymorphism means that functions can be applied to arguments of different types, different number and sequence of arguments.
The various types of parameters are specified at compile time, so the function can be bound to calls at compile time. This is called early binding.

Example of static polymorphism:
 class Program  
 {  
   class A { }   
   class B { }  
   private static void Foo(A a)   
   {   
     //something   
   }   
   private static void Foo(B b)   
   {   
     //something   
   }   
   static void Main(string[] args)  
   {   
     A a = new A();   
     Foo(a);   
     B b = new B();   
     Foo(b);   
   }  
 }  

In this example we exactly know the type of object(A or B) and corresponding Foo method that should be called.

Let's say we get object from the third-party method and we do not know exactly real type of the object(A or B). We can get this object and then cast reference to A(or to B) and call corresponding Foo method. Or we can use nifty dynamic keyword:
 public class ThirdPartyClass  
 {  
   public static IObject GetObject()  
   {  
     //something  
   }  
 }  
 class Program  
 {  
   class A { }   
   class B { }   
   private static void Foo(A a)   
   {   
     //something   
   }   
   private static void Foo(B b)   
   {   
     //something   
   }   
   static void Main(string[] args)   
   {   
     dynamic d = ThirdPartyClass.GetObject();  
     Foo(d);   
   }  
 }  

In this example, actual type of the variable d that’s declared dynamic is resolved at run time. If variable d is not of type A or B then exception will be thrown, because of trying to call method Foo with incompatible argument type.

1 comment:

  1. "Hi,
    I like your blog very much! It is found me so interesting and informative... Thanks very much for sharing this amazing information over here…"

    PIC Scheme Singapore

    ReplyDelete