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());
}
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.
There is actually no difference between using Object and dynamic in the example you have given here. There is no practical difference, and you can swap the two and the program will run the same. When I refer to "semantic difference", I mean how the code will be understood by other Dart programmers.
Difference between Dynamic and ObjectDynamic variables can be assigned with any type of value, and these variables can be assigned to any type of variable. With an object, You can declare a variable of any data.
dynamic variables can be used to create properties and return values from a function. var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.
The difference is that MyTestVar2.ToUpper()
compiles and works, without any explicit casting.
object
is a normal type.dynamic
is a basically a placeholder type that causes the compiler to emit dynamic late-bound calls.
GetType()
is a normal function defined by the object
class 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)
You should probably start with this excellent MSDN article. The differences can be summed up quite succinctly:
At compile time, an element that is typed as dynamic is assumed to support any operation.
System.Object
only has a handful of operations that it supports - ToString()
, Equals()
, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With