C# 4.0-Dynamic Data Type, Difference between var and dynamic
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.
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”;