Possible Duplicate:
Difference between “var” and “object” in C#
I would like to know the difference between var and object.
When to use Var and when to use Object.
Pros and cons of using them.
Possible Duplicate:
Difference between “var” and “object” in C#
I would like to know the difference between var and object.
When to use Var and when to use Object.
Pros and cons of using them.
var
is just shorthand for "let the compiler pick the right variable type for me" (compile-time type-inference is the more exact term).
object
, on the other hand, is a specific type; all other reference types derive from object
, so you can assign anything to a variable of type object
.
var
then as @Ben Voigt said, you can do things to the object stored in var without having to cast it.
– Eric
Jul 10 '10 at 23:42
var
is the answer when you find yourself asking, do I really have to type that long type name twice, in e.g.:
Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>> myDict = new Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>>();
Why no friend, you don't. Use var
instead:
var myDict = new Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>>();
Now myDict
really is a Dictionary<string, Func<List<Func<int, int, double>>, IEnumerable<Tuple<double, string>>>>
, so you can add things to it, enumerate it, etc.
If you declared it as object
you couldn't do any operations with it that are provided by Dictionary
, only the ones valid for all objects.
var is still strongly typed but with object you will have to cast everything.
var foo = "Hello, I am a string!";
// foo is a string, so this compiles
var fooCharArray = foo.ToCharArray();
object bar = foo;
// bar is not a string, so this does not compile
var barCharArray = bar.ToCharArray();
In the first example, the compiler knows that foo
is a string and so we can call string methods on foo
.
In the second example, we "upcast" the string foo
to an object. Now the compiler does not know (because it shouldn't know!) that bar
is actually a string, and we cannot call string methods on bar
. The compiler will not allow implicit downcasting from an object (or any base type) to a derived type (such as System.String
). Its part of compile time type safety rules.