Showing posts with label var keyword in dotnet. Show all posts
Showing posts with label var keyword in dotnet. Show all posts

Friday 30 March 2012

var keyword in dotnet

Why var keyword is used and when it is the only way to get query result?
var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalised keyword. The compiler infers the actual type from the static type of the expression used to initialise the variable. One must use var with the query that returns anonymous type. E.g. 
// anonymous type returned
var query = from w in words
            select new
                {
                    LetterCount = w.Length,
                    UpperString = w.ToUpper()
                };

foreach (var item in query)
{
    Console.WriteLine(item.LetterCount + " " + item.UpperString);
}