What is the difference between a variable declared as dynamic and a variable declared as System.Object? Running the following function would seem to indicate that both variables get cast to the correct type dynamically:
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());
}
The difference is that
MyTestVar2.ToUpper()compiles and works, without any explicit casting.objectis a normal type.dynamicis a basically a placeholder type that causes the compiler to emit dynamic late-bound calls.GetType()is a normal function defined by theobjectclass that operates on the instance that you call it on.GetType()is completely unaffected by the declared type of a variable that refers to the object you call it on. (except for nullables)