Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between dynamic and System.Object

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());
}
like image 546
Icemanind Avatar asked Aug 12 '10 01:08

Icemanind


People also ask

What is the difference between dynamic and object?

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.

What is difference between object and dynamic in Dart?

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.

What is the difference between dynamic and object in flutter?

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.

What is the difference between VAR and dynamic type?

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.


2 Answers

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)

like image 185
SLaks Avatar answered Sep 20 '22 04:09

SLaks


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.

like image 37
Igor Zevaka Avatar answered Sep 19 '22 04:09

Igor Zevaka