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.
var
everywhere. If you needed something else - you would know that. – Diffidence