views:

154

answers:

4

Hi,

As I am not familiar with implicit typing; can you please tell me the main differences between:

 var foo = new Love(); 

AND

object foo = new Love();
+15  A: 

In the first case the type of foo is Love. In the second case it is object.

Brian Rasmussen
+1 There's really nothing more to be said :D
Jonathan
Keep in mind that GetType is the same in both cases.
Giorgi
Also don't forget boxing of value types when using object :)
Arcturus
Also, remember that true love cannot be abstracted as an object.
Michael
+10  A: 
var foo = new Love(); 

Here, the static type of variable foo is Love. It's equivalent to writing Love foo = new Love();.

object foo = new Love();

Here, the static type of variable foo is object. You cannot access any of Love's methods without using a cast first.

The dynamic type (or runtime type) of foo is Love in both cases, which is why GetType will return Love for both.

Heinzi
+6  A: 

With var, the compile infers the type of the variable based on the expression on the right-hand side of the assignment operator.

In other words,

var foo = new Love();

is exactly equivalent to

Love foo = new Love();

So all the members of Love will be available via foo - whereas if foo were declared to be of type object, you'd only have access to GetHashCode(), ToString(), GetType() and Equals().

With var, you're still using static typing (as opposed to using dynamic in C# 4). You're just not explicitly stating the type of the variable - you're letting the compiler work it out for you. However, it does need to be a type that the compiler can work out. So for example, these are all invalid:

// All invalid
var a = null;
var b = delegate() { Console.WriteLine("Hello"); };
var c = x => Console.WriteLine("lambda: " + x);
var d = MethodName; // Attempted method group conversion

In these cases the compiler doesn't have enough information to work out which type you mean.

Jon Skeet
Also don't forget boxing of value types when using object :)
Arcturus
+1  A: 
var foo = new Love();

here it equals to

Love foo = new Love();

sometimes we can use var to avoid long class name e.g. Dictionary<string,Dictionary<int,string>>. You can use all methods/properties of class Love.

object foo = new Love();

Now foo is considered to be an object, you can't see any method/property of class Love, but you can convert it back.

Danny Chen