C # attributes

Source: Internet
Author: User

In C #, we can access public fields very freely and without restrictions, but sometimes we may want:

(1) only values in a certain range can be assigned to a field;

(2) The field can only be read or written;

(3) other States of the object can be changed when the field is changed;

These fields alone cannot be used, so they have attributes.

The attribute contains two blocks: set and get. The set block is responsible for writing the attribute, and the get block is responsible for reading the attribute.

You can perform other operations in both blocks, such as verifying that the assigned value meets the requirements in set and determining whether to assign values.

There must be one attribute in the set and get blocks, because the attributes that cannot be read or written are meaningless.

The following is a simple example:

(1) attributes ensure security. When not used in this class, use Attribute names to avoid field names.

1 class MyClass2 {3      private  string  name;4      public string Name5      {6          get {return name;}7          set {name=value;}8      }9 }

(2) The set and get functions of the attribute can restrict some functions of the field for a certain purpose.

1 private int A = 0; 2 Public int A 3 {4 get {return this. a;} 5 set 6 {7 if (value> = 0 & value <= 100) 8 This. A = value; 9 else10 throw new exception ("the value range is invalid. "); 11} 12}

C # attributes

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.