Monday, August 24, 2009

Dynamic in C#

Dynamic Keyword allows us to invoke things dynamically, any operations that are called on the object, will be analyzed only at the runtime and the behavior will be decided at that instance.

static void Main(string[] args)
{
dynamic d1 = 1; //1
int i = d1; //2
dynamic d2 = GetDynamicObject(); //3
d2.foo(1,2) ; //4
var x = d2 + 10; //5

}

Let us diagnose the above-mentioned code how the things are working
1. Implicit Conversion of an integer.
2. Assignment Conversion to an integer.
3. Implicit conversion of an object to dynamic, this statement will be skipped at the compile time and will be resolved only at runtime and the compiler will allow us to call a method with any name and argument.
4. As the method foo is called, compiler will instruct that at runtime method foo have to be called with two arguments. Therefore, the runtime instance of d2 will decide the method availability.
5. As the operator + is having the dynamic typed argument it will be resolved at the runtime, at runtime object d2 will search for the operator overloaded resolution for +.


Compile time: At compile time for all the dynamic lookups uses DLR (Dynamic Language Runtime). DLR takes advantage of its call sites for all the dynamic operations.

Run time: All Methods and properties are binded by using reflection

No comments:

Post a Comment