c#3.0 Tutorial: Automatic properties and Extension methods

Source: Internet
Author: User
Tags string variable

With automatic properties, you can not manually declare a private member variable and write Get/set logic, instead, the compiler will automatically generate a private variable and the default Get/set operation for you. The private variables that the system generates for you are not visible in the IDE, as shown in the following diagram:

Of course, if you want some of the attributes to be assigned or to take a logical check, automatic properties are not for you.

After we compile the above code and then use Reflector to decompile it, we can see that the attribute in the above code becomes the following code: The private variable that the compiler gives us is obviously not so easy to duplicate.


[Compilergenerated]
private String <>k__AutomaticallyGeneratedPropertyField0;

public string Name
{
[Compilergenerated]
Get
{
Return this.<>k__automaticallygeneratedpropertyfield0;

}
[Compilergenerated]
Set
{
this.<>k__automaticallygeneratedpropertyfield0 = value;
}
}

Note: If you only want the property to have a get or set method, these situations will not be able to use the automatic properties, you need to write yourself. Otherwise it will be reported as the following error:

"ConsoleApplication1.MyClass.Name.set" must declare a body because it are not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

But get and set access levels are different, such as one is public and one is internal, you can write in the following way without reporting an error.

public int ID {get; internal set;}



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.