Wednesday, January 27, 2010

New keyword 'dynamic' in framework 4.0,Difference between var and dynamic/ object and dynamic.

Hi All,

C# 4.0 introduces a new keyword called 'Dynamic'. It can consume any object anything. Let's see some examples for that.


dynamic intExample = 1;
Console.Write(intExample);

dynamic floatExample = 3.6;
Console.Write(floatExample);

dynamic stringExample = "SharpFour";
Console.Write(stringExample);


will print 13.6SharpFour

I know you will all have one question in mind that,It could be also done with var keyword . Yes, you can do same thing with var but dynamic keyword is slightly different then var keyword.

Main Diffrence between var and dynamic :

var keyword will know the value assigned to it at compile time while dynamic keyword will resolve value assigned to it at run time. I know you guys don't believe me without example. So let's take example of string.

string s = "this is test string";
var varstring=s;
Console.Write(varstring.MyMethodCall());


while compiling above code it will not compile and it gives a error that 'string' does not contain a definition for 'MethodDoesnotExist' and no extension method 'MethodDoesnotExist' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?'. So var keyword knows that what value or object or anything assigned to it. Now lets try to compile same code with dynamic example like following.


string s = "this is test string";
dynamic varstring=s;
Console.Write(varstring.MyMethodCall());


Above line of code get compile. So it is the difference between dynamic and var keyword. With dynamic keyword anything assigned to it like property,objects operators anything that will be determined at compile time. It can be useful while we are doing programming with com,JavaScript which can have runtime properties.

similar thing is applied to the keyword type 'object'. we will discuss more on 'dynamic' keyword and 'object' keyword in my next post.

Happy Coding :-)

No comments:

Post a Comment