C #3.0 Learning (3)-Anonymous type

Source: Internet
Author: User

The anonymous type is a mechanism that automatically generates a type based on the initialization list during initialization. The object initializer is used to create an anonymous object. For example:

VaR OEC = new {name = "oec2003", age = 100}

The VaR and new keywords are used in the statement for object creation. The VaR keyword is used to declare an anonymous object name. Var and object are different, and they are strongly typed, this serves as a placeholder. during compilation, the compiler will deduce the actual type. The new keyword is directly followed by a pair of braces, not the type name, because the anonymous type name is automatically generated by the compiler during compilation. The name and age in braces are anonymous type attributes. You can see that they are directly assigned after the name and age, and the type is not specified. The compiler will also infer their type, for example, after compilation, the name type is inferred to be string type, and the age type is inferred to be int type. Therefore, we can see that the anonymous type brings us a lot of flexibility and flexibility, and it also makes the code hard to understand. After the above Code is compiled, code similar to the following will be generated:

Class anonymous1 {private int _ name = oec2003; private int _ age = 100; Public int A {get {return _ name;} set {_ name = value ;}} public int B {get {return _ age;} set {_ age = value ;}}}

In the same program, if the names, types, and sequence of object initiators of different anonymous types are the same, different instances of the same anonymous type will be generated, as shown below:

VaR oec1 = new {name = "oec2003", age = 100} var oec2 = new {name = "oec2004", age = 200} oec1 = oec2

We can access Anonymous members in this way.

VaR OEC = new {name = "oec2003", age = 100} string name = OEC. Name; int age = OEC. Age

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.