C # var usage from MSDN

Source: Internet
Author: User

From Visual C #3.0, variables declared in the method range can have implicit type var. Implicit local variables are strongly typed (as if you have declared this type), but the type is determined by the compiler. The following two I declarations are functionally equivalent:

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

The following example demonstrates two Query expressions. In the first expression, var is allowed but not required, because the type of the query result can be explicitly declared as IEnumerable <string>. However,Var must be used in the second expression, because the result is an anonymous type set, and the name of this type can only be accessed by the compiler.. Note that in the second example, the foreach iteration variable item must also be converted to an implicit type.

// Example #1: var is optional because// the select clause specifies a stringstring[] 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 typevar 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 typeforeach (var item in custQuery){    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.