Dynamic and Object in C#
Dynamic and object data types in C# are very similar to one another that the C# compiler converts all dynamic variables into object datatype. That’s right, the dynamic type only exists during compilation. So, how are they different from one another?
Compile time checks
No compile time datatype checks are done to dynamic type while they are done to object datatype. For example, you can assign a dynamic variable to any datatype and no error will be thrown. But if your try to assign an object type variable into any other variable, you will need to add cast conversion.
According to official docs for dynamic,
"At compile time, an element that is typed as dynamic is assumed to support any operation.”
This means you can all any function from a dynamic variable and whether it exists or not compiler will not throw any error. You will get run-time error if the function does not exists. System.Object only supports a limited set of functions such as ToString(), Equals(), etc…
object a = "Diana Prince"; dynamic b = "Wonder women"; /* following throws compile time error */ string a1 = a; /* following compiles without error */ string a2 = (string)a; string b1 = b; a.PunchTheBadGuy(); /* throws compile time error */ b.PunchTheBadGuy(); /* compiles without error */
The datatype dynamic does not exists in run time. It gets converted into object data type.