We often see most developers unable to get what the difference is between objects and dynamic variables in C#. I have recently also tried looking at tutorials (articles) around the web, but I can't find a good solution to this. This article will explain some important points about Objects and the Dynamic keyword.
Generally, both the dynamic keyword and objects don't perform compile-time type checks and identify the type of objects at run time only and both can store any type of the variable. Objects were introduced in 1.0 C#. Later, why was Dynamic introduced in 4.0 C# when Objects already exist.
The following points defines Objects and Dynamic variables in C#.
Difference 1
- Object: the Compiler has little information about the type. It's not compiler safe.
Example:
You need to do an explicit type casting every time you want to get the value back and forth.
object a = "Rohatash Kumar";
string a1 = a.ToString();
- Dynamic: In a dynamic variable, the compiler doesn't have any information about the type of variable.
dynamic a = "Rohatash Kumar";
string a1 = a;
Difference 2
- Object: Object was introduced in 1.0 C#.
- Dynamic: Dynamic was introduced in 4.0 C#.
Difference 3
- Object: When using an object, you need to cast the object variable to the original type to use it and do the desired operations. In the first difference, the following example shows an error.
object a = "Rohatash Kumar";
string a1 = a;
Now you need to do an explicit type casting every time.
- Dynamic: Casting is not required but you need to know the properties and methods related to the stored type.
Difference 4
- Object: When we use the object keyword with a variable it can create a problem at run time if the stored value is not converted to the appropriate data type. It cannot show an error at compile time but it will show an error on run time.
Example
String a = "Rohatash Kumar";
object a1 = a;
int b = (int)a1;
Now press F5 to run the code above.
- Dynamic: When we use the dynamic keyword, it doesn't cause a problem because the compiler has all the info about the stored value.
Conclusion
Object is useful when we don't have more information about the data type. Dynamic is useful when we need to code using reflection or dynamic languages or with the COM objects and when getting result out of the LinQ queries.