ISSUE :
 
Profile photo
Submitted by Sam Buchana
on October 3rd, 2012 at 17:39:32 EST

.NET 4.0 dynamic vs var?

What is the difference between dynamic keyword with .NET 4.0 vs var which was introduced in .NET 3.0? Both seems to behave similar with variable/unknown type... Any thoughts?


Profile photo
Replied by SBajra
on October 4th, 2012 at 09:46:56 EST
When you use "var", compiler determine the type implicitly. It is declaring type implicitly based on value. However, it is still static type.

For example, both of examples below are exactly the same

var i = 10; // implicitly typed
int i = 10; //explicitly typed


With var you can not change the type once the type is implicitly determined by compiler.

For example:

var test = 1;
test = "hello"; //ERROR


However, when you use "dynamic", the variable/object type will be determined dynamically during runtime. It will ignore any compile time static type checking.

For example:

dynamic test = 1; //integer
test.foo(); //still valid because compiler will ignore the type checking and existence of test.foo() method during compile time.


for "dynamic", this is valid:
For example:

dynamic test = 1;
test = "hello"; //VALID


According to MSDN:
The dynamic type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).
Accepted Answer
Accepted
 Answer

Profile photo
Replied by Sam Buchana
on October 4th, 2012 at 13:19:33 EST
Thank you for clear explanation.