Automatic properties and object initializers in c#3.0

Source: Internet
Author: User

It is more convenient to define attributes in c#3.0 no longer in the same way as the previous version of the cumbersome, you need to define the fields to store data, and then define the property, now only need to define the property can be, the other compiler automatically for us to complete, you can omit the time required to define the field , when object initialization we can implement the initialization of object properties, similar to collection initialization.

1. Anonymous Properties

The definition attributes are as follows:

public class Employee
{
public int Id {get; set;}
public string Name {get; set;}  
public string Sex {get; set;
public int Age {get; set;}
public string Birthdate {get; set;}
}
is written before c#3.0 as follows:
public class Employee
{
private int _id;
private string _name;
Private str ing _sex;
Private int _age;
private String _birthdate;

Public int Id
{
get {_id;}
Set {_id = value;}
}
public string Name
{
get {_name;}
Set {_name = value;}
}
public string Sex
{
get {return _sex;}
Set {_sex = value;}
}
Public int:
{
get {return _age;}
Set {_age = value;}
}
public string birthdate
{
get {return _birthdate;}
Set {_birthdate = value;}
}
}

It's clear from the code that the former is 2/3 less than the latter, which is obvious for efficiency, so where does all this code go? In fact, the extra code is done for us by the compiler, and the compiler will fill in the code that we "omit" into the managed IL code, the code in the final generation of the IL Code is the same volume.

In the IL code above, we see that fields such as K_backingfield are the field codes that the compiler generates automatically.

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.