views:

338

answers:

7

The only advantage I can see to do:

var s = new ClassA();

over

ClassA s = new ClassA();

Is that later if you decide you want ClassB, you only have to change the RHS of the declaration.

I guess if you are enumerating through a collection you can also just to 'var' and then figure out the type later.

Is that it?? Is there some other huge benefit my feeble mind does not see?

+7  A: 

It's mostly syntactic sugar. It's really your preference. Unless when using anonymous types, then using var is required. I prefer implicit typing wherever possible though, it really shines with LINQ.

I find it redundant to type out a type twice.

List<string> Foo = new List<string>();

When I can easily just type var when it's obvious what the type is.

var Foo = new List<string>();
M4dRefluX
Its not purely sugar. It is required when working with anonymous types.
jrista
Correct, but even anonymous types are sugar as well.
M4dRefluX
That's like saying iterators are sugar. Sure you can build your own, but the compiler is actually doing a fair bit of work for you including nontrivial overrides on Equals, GetHashcode and ToString.
dahlbyk
@M4dRefluX: You could call a lot of things in C# "sugar", however I think a better term for it is lightweight compile-time code generation. There is a difference between simple syntactic prettieness, and the complex code generation that the C# compiler does for you when it takes things like LINQ queries, iterators, anonymous types, etc. and turns them into "normal" code. I would call anonymous delegates sugar, but I would call an anonymous type useful code generation that saves me time, effort, and money.
jrista
@jrista: I agree, they are definitely a time saver, just like the var keyword. I think we have different definitions. Syntatic sugar to me is a feature that saves me from typing redundant code.
M4dRefluX
+3  A: 

I started what turned out to be a hugely controversial thread when I first signed on here (my choice of "evilness" to describe general use of var was obviously a terrible choice.) Needless to say, I have more appreciation for var than I did before I started that thread, as well as a better understanding of how it can be usefully used:

http://stackoverflow.com/questions/902563/the-evilness-of-var-in-c-closed

Some good reasons to use var:

  • Brevity
  • Reduction of Repetition (DRY)
  • Reduced refactoring effort
  • Supports anonymous types (key reason it was added to C#)
jrista
+3  A: 

Have a look at this questions. Maybe they'll help you decide.

http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c
http://stackoverflow.com/questions/633474/c-do-you-use-var

Lucas McCoy
A: 

The overarching reason for the implicit typing was to support anonymous types, like those produced by LINQ queries. They can also be a big benefit when dealing with complex-typed generics...something like Dictionary<int,List<string>>. That's not too complex, but imagine enumerating...

foreach KeyValuePair<int,List<string>> pair in myDictionary
{

}

is simplified with implicit typing.

Adam Robinson
A: 

It allows me to not repeat myself unnecessary. Consider this:

Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

We have a very long typename repeated twice on the same line twice with absolutely no benefit. Furthermore, if you ever need to refactor this, you'll need to update the type twice. Whereas this is just as expressive:

var dict = new Dictionary<string, List<int>>();

There's still no doubt about type of dict here, but the code is shorter, and I would claim that it is easier to read as well.

Pavel Minaev
+2  A: 

var is useful for anonymous types, which do not have names for you to use.

var point = new {X = 10, Y = 10};

This will create an anonymous type with properties X and Y. It's primarily used to support LINQ though. Suppose you have:

class Person
{
    public String Name {get; set;}
    public Int32 Age {get; set;}
    public String Address {get; set;}
    // Many other fields
}

List<Person> people; // Some list of people

Now suppose I want to select only the names and years until age 18 of those people who are under the age of 18:

var minors = from person in people where person.Age < 18 select new {Name = person.Name, YearsLeft = 18 - person.Age};

Now minors contains a List of some anonymous type. We can iterate those people with:

foreach (var minor in minors)
{
    Console.WriteLine("{0} is {1} years away from age 18!", minor.Name, minor.YearsLeft);
}

None of this would otherwise be possible; we would need to select the whole Person object and then calculate YearsLeft in our loop, which isn't what we want.

Nick Lewis
A: 

While the var keyword was primarily introduced to support anonymous types, the main argument I've seen for using it more widely is for brevity/more readable code, plus fitting more on your line of code:

Dictionary<string, double> data = new Dictionary<string, double>();
versus
var data = new Dictionary<string, double>();

Though not a good reason for most people, I also like the var keyword as a blind programmer, as I listen to the code being read out and thus here the variable name after just one syllabul :-)

Saqib