Monday, July 25, 2011

How dynamic in c# 4.0 works

In this Post i will try to give an idea what "dynamic" keyword do.

Have a loot at the following Program class, in the constructor of the program class i am calling StartDeveloperWork and StartDynamicWork methods by passing similar objects in the order.



class Program
{

public Program()
{
//Case 1
StartDeveloperWork(new Developer());
StartDeveloperWork(new ASPNetDeveloper());
StartDeveloperWork(new WPFDeveloper());

//Case 2
StartDynamicWork(new Developer());
StartDynamicWork(new ASPNetDeveloper());
StartDynamicWork(new WPFDeveloper());
}

public void StartWork(Developer d)
{
d.Work();
}

public void StartWork(dynamic d)
{
d.Work();
}
}


class WPFDeveloper : Developer
{
public void Work()
{
Console.Write("WPFDeveloper ");
}
}

class ASPNetDeveloper : Developer
{
public void Work()
{
Console.Write("ASPNetDeveloper ");
}
}

class Developer
{
public void Work()
{
Console.Write("Developer ");
}
}


but the out put displayed for startdeveloperwork will be
Developer
Developer
Developer


and out put displayed for StartDynamicWork will be

Developer
ASPNetDeveloper
WPFDeveloper

.. because we in Developer class we have not marked work method as Virtual so when we are calling with base class reference the method in the base calls will be called.

in the StartDeveloperWork method we are using base class reference for calling work method.

coming to StartDynamicWork we are using dynamic keywork means the type of object will be decided at runtime. so method in the passed object will be called.
if the method is not there in the passed object then it will go to base class for the same method. if the method is not there in base class also then it will throw an target invocation exception.

So be care full and make yourself clear when to use and when not to use

No comments:

Post a Comment