var (C# 參考)var (C# Reference)

從 Visual C# 3.0 開始,在方法範圍內宣告的變數可以使用隱含的「類型」varBeginning in Visual C# 3.0, variables that are declared at method scope can have an implicit "type" var. 隱含型別區域變數如同您自己宣告的類型一樣是強型別,但是編譯器會判斷類型。An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. 下列兩個 i 宣告的功能相同:The following two declarations of i are functionally equivalent:

var i = 10; // Implicitly typed. 
int i = 10; // Explicitly typed. 

如需詳細資訊,請參閱隱含型別區域變數LINQ 查詢作業中的類型關聯性For more information, see Implicitly Typed Local Variables and Type Relationships in LINQ Query Operations.

範例Example

下例示範兩個查詢運算式。The following example shows two query expressions. 在第一個運算式中允許使用 var,但並非必要,因為查詢結果的類型可以明確陳述為 IEnumerable<string>In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>. 不過,在第二個運算式中,var 允許結果是匿名型別的集合,而且只有編譯器本身才能存取該型別的名稱。However, in the second expression, var allows the result to be a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. 使用 var 就不需要建立結果的新類別。Use of var eliminates the requirement to create a new class for the result. 請注意,在範例 #2 中,foreach 反覆運算變數 item 必須也是隱含型別。Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required when
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}

請參閱See Also