Difference between Object, Dynamic and Var
Solution 1
Everything is Object
because it is a base type for every type in .net environment. Every type inherit from Object
in a moment, a simple int
variable can be boxed to an object
and unboxed as well. For example:
object a = 10; // int
object b = new Customer(); // customer object
object c = new Product(); // product object
object d = "Jon"; // string
object e = new { Name = "Felipe", Age = 20 }; // anonymous type
It is the most abstraction for any type and it is a reference type. If you want to get the real type, you need to unbox
it (using a conversaion strategy such as methods, casts, etc):
object a = "Some Text";
string text = a.ToString();
// call a string method
text = text.ToUpper();
object i = 10; // declared as object but instance of int
int intValue = (int) i; //declare as an int ... typed
Dynamic
is an implementation of a dynamic aspect in C#, it is not strongly typed. For example:
dynamic a = new Class();
a.Age = 18;
a.Name = "Jon";
a.Product = new Product();
string name a.Name; // read a string
int age = a.Age; // read an int
string productName = a.Product.Name; // read a property
a.Product.MoveStock(-1); // call a method from Product property.
var
is just a keyword of the C# language that allows you define any object of a type since you initialize it with a value and it will determinate the type from this value, for example:
var a = 10; // int
var b = 10d; // double
var c = "text"; // string
var d = 10m; // decimal
var p = new Product(); // Product type
The compiler will check the type of the value you have defined and set it on the object.
Solution 2
Object:
Each object in C# is derived from object type, either directly or indirectly. It is compile time variable and require boxing and unboxing for conversion and it makes it slow. You can change value type to reference type and vice versa.
public void CheckObject()
{
object test = 10;
test = test + 10; // Compile time error
test = "hello"; // No error, Boxing happens here
}
Var:
It is compile time variable and does not require boxing and unboxing. Since Var is a compile time feature, all type checking is done at compile time only. Once Var has been initialized, you can't change type stored in it.
public void CheckVar()
{
var test = 10; // after this line test has become of integer type
test = test + 10; // No error
test = "hello"; // Compile time error as test is an integer type
}
Dynamic:
It is run time variable and not require boxing and unboxing. You can assign and value to dynamic and also can change value type stored in same. All errors on dynamic can be discovered at run time only. We can also say that dynamic is a run time object which can hold any type of data.
public void CheckDynamic()
{
dynamic test = 10;
test = test + 10; // No error
test = "hello"; // No error, neither compile time nor run time
}
Solution 3
1) var
is used for implicit type definition. For example if you define a variable like this:
var number = 123;
Compiler infers the type based on the assigned value and your variable initialized as integer in compile time. After this definition you can't assign a string
to your variable because it is an integer.And you can't use var
like this:
var number;
number = 123;
Because you have to assign something to your variable if you are using var
keyword so that the type can be determined.
2) Object
is a base class for all classes. In C#
all classes inherits from object class, therefore you can assign everything to an object.For example:
object str = "bla bla bla...";
str = 234;
str = DateTime.Now;
This is working because when you doing this boxing/unboxing performing automatically for you. And as opposed to var
keyword you can use object
like this:
object myVariable;
myVariable = "bla bla bla..";
3) dynamic
is a cool feature that came with C# 4.0
, you can use dynamic
if you don't know returning type from your function in compile time.Your type will be determined in run-time
.Therefore you can't use intellisense with dynamic variables.
You can use dynamic like this:
dynamic myObj = SomeMethod();
myObj.DoSomething();
myObj.Method1();
But you must be careful when you are using dynamic.Because if you call a method or property which doesn't exist you will get a RuntimeBinderException
in runtime.
And last thing I want to mention, dynamic
and object
can be parameter type, but var
can't. For example you can do this:
public void SomeMethod(dynamic arg1)
But you can't do this:
public void SomeMethod(var arg1)
Because var
is not a type rather it's a syntactic sugar to let the compiler infer the type for you.
Solution 4
Object
is the root class that all .net objects derive from.
var
is used as a shortcut if you don't want to write say string x = "a"
, but instead write var x = "a"
. It only works if the compiler can figure out what you mean.
dynamic
implies that what you do with the object is only evaulated at runtime (x.StrangeMethod()
will not cause a compile error, even if the method does not exist), useful when interacting with scripting languages.
Solution 5
It’s pretty simple…
Object is a base type in .NET. All others types are inherit from it. So variable of object type can contain everything. But it should be done only there are no other options, for the following reasons:
Before read/write to this variable we have to done unboxing/boxing operations, which are expensive.
Compiler can’t do type checking at compile time that may result bugs and exceptions at run time. For example this code will be compiled successfully but throw an exception at run time:
object o = "2"; int i = 1 + (int)o;
Var is not a type, but the instruction for the compiler to conclude a variable type from the program context. It needed for anonymous methods but also can be used everywhere you wish. Beware only your program not became hard to read. The compiler makes its decision at compile time so it will not any influence on program efficiency.
Dynamic – is a special type for which the compiler don’t do type checking at compile time. The type is specified at run time by CLR. This is static (!) type and after the variable type is specified, it can not later be changed. We should use this type only there are no other options for similar reasons with object type:
There is an addition operation to specify the type at run time - which reduces the program efficiency.
Compiler don’t perform type checking that may result bugs and exceptions at run time.
Lamloumi Afif
Hi, I am a Software Development Engineer with a genuine interest in .Net framework. I enjoy reading books and practising sport. LinkedIn Viadeo
Updated on January 27, 2021Comments
-
Lamloumi Afif over 3 years
I need to know the difference between these three keywords
Object
,Dynamic
andvar
in C#.I have seen this link but i don't understand in which case i have to use each one.
Can you explain for me, please, the difference between these keywords ? What are the utilities of each keyword?
-
Haithem KAROUI about 7 yearsBest answer so far... all other answer are saying the same thing about object : "base type in .net shit" ... but the guy just asked for THE DIFFERENCE between Dynamic and Object ... he did not ask for the definition of object...
-
ProgrammingLlama over 5 yearsSince this answer was just plagiarised elsewhere, I'll add my comment where here: it should be noted that
dynamic
doesn't change the underlying type, so callinga.FavouriteFood = "pizza";
would throw an exception at runtime, becauseClass
doesn't defineFavouriteFood
. -
Zohar Peled over 5 yearsThis is by far the best answer it this post. Unfortunate that both the accepted answer and the highest rating answer both contains mistakes, while the best answer has such a lower score in comparison.