9

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.

Community
  • 1
  • 1
Sandeep
  • 7,156
  • 12
  • 45
  • 57
  • Looks extremely similar to http://stackoverflow.com/questions/1552881/difference-between-var-and-object-in-c – Mathias Jul 10 '10 at 23:19

4 Answers4

22

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.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
  • 4
    Unless it's a primitive, in which case it must be boxed before being assigned into the `Object` reference. – Billy ONeal Jul 10 '10 at 23:15
  • I think something that should be added to the selected answer is that if you use 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
14

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
6

var is still strongly typed but with object you will have to cast everything.

Craig
  • 36,306
  • 34
  • 114
  • 197
5
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.