logo
CSharp_Prog_Guide

Var и анонимные типы

Во многих случаях использование ключевого слова var является необязательным, оно служит лишь для синтаксического удобства. Однако это ключевое слово необходимо при инициализации переменной с анонимным типом. Этот сценарий является типичным в выражениях запроса LINQ. Дополнительные сведения см. в разделе Анонимные типы.

Поскольку имя анонимного типа известно только компилятору, в исходном коде следует использовать ключевое слово var. Если переменная запроса инициализирована с var, ключевое слово var также должно использоваться в качестве типа переменной итерации в операторе foreach, который выполняет итерацию по переменной запроса.

-----

Remarks

The following restrictions apply to implicitly-typed variable declarations:

The only scenario in which a local variable must be implicitly typed with var is in the initialization of anonymous types.

You may find that var can also be useful with query expressions in which the exact constructed type of the query variable is difficult to determine. This can occur with grouping and ordering operations.

The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code. One example where var is helpful in this manner is with nested generic types such as those used with group operations. In the following query, the type of the query variable is IEnumerable<IEnumerable<Student>>. As long as you and others who must maintain your code understand this, there is no problem with using implicit typing for convenience and brevity.

// Same as previous example except we use the entire last name as a key.

// Query variable is an IEnumerable<IGrouping<string, Student>>

var studentQuery3 =

from student in students

group student by student.Last;

However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.