var(C# 참조)

업데이트: 2007년 11월

메서드 범위에서 선언된 변수는 암시적 형식 var를 가질 수 있습니다. 암시적으로 형식화된 지역 변수는 형식 자체를 선언했던 것처럼 강력하게 형식화되었지만 컴파일러에서 형식을 결정합니다. 다음의 i의 두 선언은 기능면에서 동일합니다.

var i = 10; // implicitly typed
int i = 10; //explicitly typed

자세한 내용은 암시적으로 형식화된 지역 변수(C# 프로그래밍 가이드)쿼리 작업의 형식 관계(LINQ)를 참조하십시오.

예제

다음 예제에서는 두 개의 쿼리 식을 보여 줍니다. 첫 번째 식에서 var의 사용은 허용되나 쿼리 결과의 형식이 IEnumerable<string>로 명확하게 지정되기 때문에 필요한 것은 아닙니다. 그러나 두 번째 식에서는 결과가 익명 형식의 컬렉션이고 형식의 이름이 컴파일러 자체 이외에는 액세스할 수 없으므로 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);
}

참고 항목

개념

C# 프로그래밍 가이드

참조

암시적으로 형식화된 지역 변수(C# 프로그래밍 가이드)

기타 리소스

C# 참조