Introduction
The Object type has existed since the beginning of C#, in other words, C# 1.0, and exists at System. Object. Var comes next in C# 3.0, followed by the dynamic keyword in C# 4.0.
Object
Now object comes from C# 1.0 and derives from System. Object, and we can assign any value to this reference.
What's the difference between var and dynamic?
- var was introduced in C# 3.0. Dynamic was introduced in C# 4.0.
- var is statically typed; in other words, the data type of var is inferred at compile time. Dynamic is a dynamic type, and the value type is inferred at runtime.
- Vars are initialized during declaration. A dynamic can be initialized at runtime.
- Var cannot be used to create a return type of a function or property. Dynamic can be used as the return type or properties.
- var cannot change the data type. A dynamic can change its data type later.
As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time." -MSDN.
The following is the usage of these two.
That can now be written simply as.
Difference between object and dynamic
Dynamic tells the compiler that the data type can be anything, so the compiler doesn't interfere, and dynamic gives no compile-time error but will definitely give a runtime error if all is not good (in other words, runtime error.
The following code will work properly for dynamic, but not if the dynamic is replaced by the object. (The reason is explained in the preceding object-type discussion.
So if Dynamic can take any data type, can we pass it to another function expecting something other data type and crash.
Assume we have a function.
Now we have.
Here, the first one will not compile, and the second one will compile but give a runtime error.
What is Dynamic Suppresses the Compiler Logic
With the dynamic keyword, one interesting object comes out to be ExpandoObject.
In order to emulate the dynamic functionality of adding members to objects at runtime, .Net comes with the IDynamicMetaObjectProvider interface. Classes implementing it will have a full dynamic behavior.
A useful class in version 4 of the .NET Framework is ExpandoObject. It is a built-in implementation of the IDynamicMetaObjectProvider interface and it allows dynamically adding members at runtime, like in the following example.
The code is taken from MSDN. This has the following two interesting features.
- They are used to reduce the number of lines of code. We do not need to write the type name again and again.
- They are used extensively in anonymous methods. You wouldn't be able to declare a variable of an anonymous type if you always need to include the type name as part of the variable declaration.
- COM interop.
- Reading XML, JSON without creating custom classes.