The difference between dynamic and System.Object

What is the difference between a variable declared as dynamic and a variable declared as System.Object? The execution of the following function, it would seem, indicates that both variables get a dynamic type:

void ObjectTest() { System.Object MyTestVar = "test"; dynamic MyTestVar2 = "Testing 123"; Console.WriteLine("{0}", MyTestVar.GetType()); Console.WriteLine("{0}", MyTestVar2.GetType()); MyTestVar = 123; MyTestVar2 = 321; Console.WriteLine("{0}", MyTestVar.GetType()); Console.WriteLine("{0}", MyTestVar2.GetType()); } 
+7
variables c # dynamic
source share
3 answers

The difference is that MyTestVar2.ToUpper() compiles and works without any explicit cast.

object is a normal type. dynamic is basically a placeholder type that causes the compiler to emit late-delayed dynamic calls.

GetType() is a normal function defined by the object class that runs on the instance you call it on.
GetType() completely independent of the declared type of the variable, which refers to the object you are calling. (excluding acceptable values)

+6
source share

You should probably start with this excellent MSDN article . The differences can be summarized quite briefly:

At compile time, an element that is typed as dynamic is supposed to support any operation.

System.Object has only a few operations that it supports - ToString() , Equals() , etc.

+1
source share

The main difference is the compilation time (for the object) and the execution time (for the dynamic) call forwarding. It is also called early and late binding. [Note: add a link to Microsoft.CSharp to compile the following code.]

  object o = "Hello world";// fine because a derived type can be assigned to a base type dynamic d= "Hello world";// fine as well Type otype=o.GetType();// compiles because it confirms that object has a GetType() Type dtype=d.GetType();// also compiles but for another reason (ieno binding yet) string upperd= d.ToUpper(); // compiles because no binding yet ( anything goes :) string uppero= o.ToUpper(); // Fails to compile. Object has no ToUpper() method 

If you comment on the last call, the application should work fine, because the CLR, when it reaches the second last call to d.ToUpper () at run time, will look for the ToUpper () method in the string type and find it there (because in the second statement d a string has been assigned). The last call did not compile, because during compilation in the System.Object style, a search for ToUpper () was performed, which, of course, would not be.

+1
source share

All Articles