This tutorial shows you how to distinguish the Object and Dynamic data types in C# code.
We often find that most developers do not distinguish the difference between object and dynamic variables in C# code. I tried to find tutorials on the web, but could not find a reasonable solution to this problem. This article will explain some important fundamentals about the difference between object and dynamic keywords in C#.
In general, both dynamic and objects do not perform type checking when compiling and are identified with the type of variables at run-time, when running the program both can be stored values of any type. Object is introduced in C# 1.0. Then why dynamic was introduced at 4.0 when the object already exists.
Notice the following differences between object and dynamic variables in C#:
Difference 1
Object: The compiler has a section of information about the type of variable, which is not a safe compile type.
For example:
You need to switch explicitly every time you want to get the value of the variable
object o = "CSharpCode";
string s = o.ToString();
Dynamic: The compiler does not have any information about the type of variable
dynamic d = "CSharpCode";
string s = d;
Difference 2
Object: Introduced in C# 1.0.
Dynamic: Introduced in C# 4.0.
Difference 3
Object: When using an object, you need to pass the object variable type to its original type for use in desired purposes.
In the number 1 difference, the example below gives an error
Dynamic: Type conversion is not required unless you may need to know the properties and methods related to the data type.
Difference 4
Object: When you use the object keyword with a variable, it can generate an issue when executing if the stored value does not switch to the corresponding data type. It may not display an error at compile time but it will display an error at execution time.
For example
String s = "CSharpCode";
object o = s;
int b = (int)o;
Dynamic: When we use dynamic keyword, it will not happen because the compiler has all information about the stored value.
Object is useful when you don't have more data type information. Dynamic is useful when you need code using reflection or dynamic language or COM objects and when retrieving values from a LinQ query.