c#3.0 Learning

Source: Internet
Author: User

An anonymous type is a mechanism for automatically generating types based on initialization lists at initialization time, using object initializers to create objects of anonymous objects. Such as:

var oec=new {name= "oec2003", age=100}

Using the Var and new two keywords in the statement that created the object,

The var keyword is used to declare an object name of an anonymous type, unlike Var and object, which is a strong type, where it acts as a placeholder, and the compiler infers the actual type.

The new keyword is directly followed by a pair of curly braces, not a type name, because the name of the anonymous type is generated automatically by the compiler at compile time. The name and age of the curly braces are anonymous types of attributes, which can be seen to be directly assigned after name and time, without specifying the type, and by the compiler to infer their type, for example, after compiling name inferred to string and age to int. So we can see that the anonymous type gives us a lot of respect and flexibility, and it makes the code difficult to read.

The code above is compiled to produce a code similar to the following

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 name, type, and order of the object initializers in the different anonymous types defined are the same, a different instance of the same anonymous type will be Immortal, as follows:

var oec1=new {Name="oec2003" ,Age=100}
var oec2=new {Name="oec2004" ,Age=200}
oec1=oec2

We can access members of anonymous types like this

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.