C# var usage from MSDN

1493 ワード

Visual C#3.0から、メソッド範囲で宣言された変数に暗黙的なタイプvarを含めることができます.暗黙的なタイプのローカル変数は、強いタイプ変数です(タイプを宣言したように)が、コンパイラによってタイプが決定されます.次の2つのi宣言は、機能的に同等です.
var i = 10; // implicitly typed

int i = 10; //explicitly typed


次の例では、2つのクエリー式を示します. 
最初の式では、varは使用できますが使用する必要はありません.なぜなら、クエリ結果のタイプをIEnumerableと明示的に宣言できるからです. 
ただし、2番目の式ではvarを使用する必要があります.結果は匿名タイプの集合であり、このタイプの名前はコンパイラ自体のみがアクセスできます.
第2の例では、foreach反復変数itemも暗黙的なタイプに変換する必要があります.

 
   
// 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 because

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

}