APPLY LATE BINDING IN .NET 4.0 AND DIFFERENTIATE IT WITH VAR KEYWORD


Below is a classic late binding code of VB6.0
 Dim Foo as Object
 Set Foo = CreateObject(“MyObject.MyClass”)
 Normally they are using a key word Set to assign some dynamic type and compiler will ignore this during compilation and only evaluate during run time. How we can achieve this in C#. Many of you thinking about object type. But once you received object type, you need to cast it to a correct type. Casting itself taking lot of resources. Not all types suporting Generics too. So in 4.0 version we have keyword dynamic and we can use it like below
dynamic d = 10;
d="Jaish the great";
Now d can store any type like var key word. Your next question would be the difference between var and dynamic, as
both can store any types, what dynamics need?
Differentiate var and dynamics
var - Identifying it's assigned type during compilation time itself.
dynamic - Identifying it's assigning tye during run time only.
Try below simle example for dynamics. It's using int.Parse() and passing an integer as an argument in lace of sting. But once you compiled no errors will get, as all these assignments  not evaluating during compile time. But once you try to run the code, ofcouse will be broken
dynamic d = 10;
int.Parse(d);

Now try the same for var keyword like below

var d = 10;
int.Parse(d);

Same mistake we wrote, but this time you will get error during compile time itself.
S above two examples a solid proof that dynamic is latebinding and var is static binding. This is the main
difference between these two general storage types.
Lastly a simle example like from where we can use Latebinding and dynamics. Below we have class with 2 methods.
Both will process some message. It's common that big manipulated messages in StringBuilder format and straing
simple message in string format. Based on these argument types each methods need to be called dynamically.
public class MyClass
    {
      
        public string HandleMessage(string s)
        {
             //Process message
  return s;
        }
        public string HandleMessage(StringBuilder s)
        {
                //Process message
  return s.ToString();
        }
}
My calling part using dynamic to call these methods dynamically.
  
  MyClass obj = new MyClass();
    dynamic s = string.Empty;

     s = new StringBuilder();
  //This will call 2nd HandleMessage method
    obj.HandleMessage(s);

   s = "Message";
  //This will call 1st HandleMessage method
  obj.HandleMessage(s);

Now you try to implement the same with var keyword and make sure you are very fine with the difference between
both them. Also try to aly dynamics in COM interaction coding where lot of dynamics types are there.
Ebook Download
View all
Learn
View all