C# 4.0-Dynamic Data Type, Difference between var and dynamic

C# 4.0-Dynamic Data Type, Difference between var and dynamic

http://www.facebook.com/plugins/like.php?href=http://www.dotnetjalps.com/2009/11/c-40-dynamic-data-type-difference.html&layout=standard&show_faces=false&width=90&action=like&font=arial&colorscheme=light inShare0
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;
Response.Write(intExample);dynamic floatExample = 2.5;

dynamic stringExample = “DotNetJaps”;


It will print out put on web page as following.


Now, you will have question what’s new in 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.

Diffrence between var and dynamic keyword:

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 = “DotNetJaps-A Blog for asp.net,C#.net,VB.NET”;
var varstring=s;


Now try to compile 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 = “DotNetJaps-A Blog for asp.net,C#.net,VB.NET”;
dynamic varstring=s;


This will 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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: