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;Response.Write(floatExample);dynamic stringExample = "DotNetJaps";
Response.Write(stringExample);
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;Response.Write(varstring.MethodDoesnotExist());
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;Response.Write(varstring.MethodDoesnotExist());
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.Happy Programming…