Set {Variable = value;} get {return variable;}, valuereturn

Source: Internet
Author: User

Set {Variable = value;} get {return variable;}, valuereturn

Shape:

Public string _ customValue
{
Set {_ customValue = value ;}
Get {return _ customValue ;}
}

This is an attribute used to encapsulate fields. Generally, fields in the class are private, and external direct access is not allowed. They must be accessed through attributes. This improves security and is a standard for coding.
You can also perform some operations in the attribute, which are invisible to external visitors, and rewrite the get and set methods.
Get is used to obtain the field value, and set is used to set the field

In c #, what is the use of the get {return field;} set {field = value?

This is the property. Attributes allow external programs to access your private fields (provided that your attributes are public ).
However, the biggest function of an attribute is to process fields in get and set, including determining the range and evaluation. This ensures the correctness of the data and ensures that the field values are correct and timely when you read the data.
I personally think that the most important role of an attribute is to make a read-only attribute or write only the attribute. This is the most useful. It controls the reading and writing of fields and ensures the correctness of the program.

C # get and set usage

First, get and set are two methods unique to the property. Attributes encapsulate fields to ensure the security of program data. In general, the field has two operation permissions: get and modify, which correspond to the get and set methods respectively. You can define the get and set methods to limit the field access permissions.
For example:
Private int _ age; // age field public int? Age {get {return _ age;} set {if (_ age <0 | _ age> 150) _ age = null; else _ age = value ;}}

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.