tags:

views:

643

answers:

8

Duplicate:

What to use var or object name type

I couldn't understand the need of var keyword in C# 3.0 What is the advantage in using it. i saw this question but did not understand the real purpose of using it

A: 

The highest voted answer to that other question explains it about as clearly as it could possibly be explained, I think.

Daniel Earwicker
+1  A: 
  • Linq expressions don't return a predefined type, so you need a 'generic' variable declaration keyword to capture that and other places where anonymous types are used.
  • Used carefully, it can make refactoring easier by decoupling a method's return type from the variable that captures it.
  • Having to put the same name on the same line twice for the same statement is really kind of silly. It's a pain to type something like this:

.

ReallyLongTypeName<SomeOtherLongTypeName> MyVariable = new ReallyLongTypeName<SomeOtherLongTypeName>();
Joel Coehoorn
Often I wish you could do this instead: ReallyLongTypeName myVariable = new ();
BFree
@BFree: I think VS effectively does that.
Mehrdad Afshari
+3  A: 

The primary reason for its existence is the introduction of anonymous types in C#. You can construct types on the fly that don't have a name. How would you specify their name? The answer: You can't. You just tell the compiler to infer them for you:

var user = users.Where(u=> u.Name == "Mehrdad")
                .Select(u => new { u.Name, u.Password });
Mehrdad Afshari
+8  A: 

It's mostly present for LINQ, when you may use an anonymous type as the projection:

var query = from person in employees
            where person.Salary > 10000m
            select new { FullName=person.Name, person.Department };

Here the type of query can't be declared explicitly, because the anonymous type has no name. (In real world cases the anonymous type often includes values from multiple objects, so there's no one named class which contains all the properties.)

It's also practically useful when you're initializing a variable using a potentially long type name (usually due to generics) and just calling a constructor - it increases the information density (reduces redundancy). There's the same amount of information in these two lines:

List<Func<string, int>> functions = new List<Func<string, int>>();
var functions = new List<Function<string, int>>();

but the second one expresses it in a more compact way.

Of course this can be abused, e.g.

var nonObviousType = 999999999;

but when it's obvious what the type's variable is, I believe it can significantly increase readability.

Jon Skeet
When the type safty of visual studio and the compiler keeps track of all of this for you why not use it like you could a loosely typed system. It can make refactoring in the future much easier. Also I know there are some times such as your "var nonObviousType = 999999999;" example when you should probably declare the type to help out the compiler.
Matthew Whited
+1  A: 

It's a shorthand way of declaring a var. Although "int i = new int()" isn't too much to type, when you start getting to longer types, you end up with a lot of lines that look like:

SomeReallyLong.TypeName.WithNameSpaces.AndEverything myVar = new SomeReallyLong.TypeName.WithNameSpaces.AndEverything();

It eventually occurred to someone that the compiler already knew what type you were declaring thanks to the information you were using to initialize the var, so it wouldn't be too much to ask to just have the compiler do the right thing here.

D. Lambert
+1  A: 

Here are a couple of advantages

  1. Less typing with no loss of functionality
  2. Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
  3. Makes it so you don't have to write the same name twice in a variable declaration.
  4. Some features, such as declaring a strongly typed anonymous type local variable, require the use of var

Shameless self promotion. I wrote a blog entry on this subject awhile back that dived into when I thought the use of var was appropriate and contains relative information to this topic.

JaredPar
A: 

In short:

  1. minimize the need for typing the variable type twice
  2. essential in supporting anonymous types, e.g. as returned by LINQ queries
Peter Lillevold
A: 

The real need for the var keyword was to support anonymous types in C# 3.0--which in turn were required to properly support LiNQ (Language Integrated Querying).

Without using var you could never do something like this:

 var person = new { Name = "Peter", Age=4};

Which means that you couldn't execute execute the following linq query because you wouldn't know how to assign it to a variable:

[var/sometype] dogsFixedQuery = from myDog in kennel select new {dogName = myDog.FirstName + " " + myDog.OwnerLastName, myDog.IsNeutered, dogLocation = kennel.Address};

The utility of anonymous types will be more apparent if you start to create more complex linq queries with multiple levels of returns and joins.

The fact that you can use var in other ways to avoid typing out something like IEnumerable<Dictionary<List<string>,IOrderedCollection<DateTime>> myBadDesign = getBadDesignController().BadDesignResults("shoppingCart"); is just a side-effect/bonus in case you're a lazy typer =)

There are cons for readability if you start calling vars in disparate locations but if you're using var for a strong type and the compiler can determine the type of your variable than any reader should be able to determine it as well.

nvuono