Advantage of var keyword in C# 3.0

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


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, eg

var nonObviousType = 999999999;

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


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 });

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.

链接地址: http://www.djcxy.com/p/53808.html

上一篇: 为什么C#需要集成类型已经有了“Var”关键字?

下一篇: C#3.0中var关键字的优点