Tuesday, August 16, 2011

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

2 comments:

  1. A beautiful and high quality information.this paper is accurate to be useful. Thanks to the author.

    PIC Scheme Singapore

    ReplyDelete
  2. I just started using Joomla and am having trouble finding good template galleries. Any suggestions? cheap essay writing service uk

    ReplyDelete