Differences in properties and fields in C #

Source: Internet
Author: User

The difference between a property and a field

In C #, we have a very free, unrestricted access to public fields, but in some cases we may want to limit the values that can only be assigned to a field, or to require fields to be read-only or write-only, or to change some other state of an object when changing a field, which cannot be done by a single field. Then there is the attribute, which contains two blocks: Set and Get,set block are responsible for the writing of the property, the get block is responsible for the property read work. There are a few other things you can do in two blocks, such as verifying that the assigned value meets the requirements in set and deciding whether to assign a value. When one of the pieces is missing, the property is only readable or writable, and the properties in the set and get blocks must have one, because a property that cannot be read and cannot be written is meaningless.

Class MyClass

{

Private string name;

public string Name

{

get {return Name;}

set {Name=value;}

}

}

(1) Attributes are guaranteed to be secure, and when not used in this class, it is guaranteed that property names can be used to avoid

Use the name of the field.

(2) The set and get functions of a property can limit some of the functions of a field for some purpose.

 

Such as:

 

private int a=0;

public int a{Get{return THIS.A;}         set {if (value >= 0 && value <=) This.a=value; else throw new Exception ("The range of values is not valid.     ");  }} (3) property does not have the ability to store data, the data exists in the field, so only modifying the field's data can change the data, modifying the value of the property is useless. Forwarding Address: http://www.cnblogs.com/yichengbo/archive/2011/07/31/2122916.html

Differences in properties and fields in C #

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.