What is the exact use of var keyword?

Possible Duplicate:
Use of var keyword in C#

After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?

For example I rather lazily used var in questionable circumstances, eg:-

foreach(var item in someList) { // ... } // Type of 'item' not clear.
var something = someObject.SomeProperty; // Type of 'something' not clear.
var something = someMethod(); // Type of 'something' not clear.

More legitimate uses of var are as follows:-

var l = new List<string>(); // Obvious what l will be.
var s = new SomeClass(); // Obvious what s will be.

Interestingly LINQ seems to be a bit of a grey area, eg:-

var results = from r in dataContext.SomeTable
               select r; // Not *entirely clear* what results will be here.

It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.

It's even worse when it comes to LINQ to objects, eg:-

var results = from item in someList
              where item != 3
              select item;

This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.

There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type.


Personally I find the circumstances you describe far from questionable, since there is no point in repeating yourself unless you specifically want the static type of a variable to be different than the static type of the expression used to initialize the variable. For example:

IEnumerable<int> foo = new List<int>(); // It's IEnumerable on purpose

Furthermore, there are absolutely no type safety concerns with var . The point is not that the variable can be of "any" type. It is of a very specific type, but you simply do not care to spell that type out.


I'm only using it as a place holder until I'm sure which datatypes I'm using.

Sure this is a short answer but I think it's pretty close that when you should use the var keyword.


the var keyword is used as shorthand in the language, but isn't a .NET type. The compiler must know the type of the variable to use the var keyword - so it is type-safe.

I personally only use it if the type name is also used in the assignment and the name is possible too long to duplicate in the code.

var dictionary = new Dictionary<string, string>();

It is also used for anonymous types (but still, the compiler must know the signature of the anonymous type).

var fred = new { Age = 23, Name = "Fred" };

This method is used commonly in the select clause of LINQ queries.

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

上一篇: 双重问号在C#中做什么?

下一篇: var关键字的确切用法是什么?