C# Properties
What are Properties?
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.
This feature enables data to be accessed easily and still helps promote the safety (Encapsulation) and flexibility of methods.
Properties overview
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
A
get
property accessor is used to return the property value, and aset
property accessor is used to assign a new value.The
value
keyword is used to define the value being assigned by the set accessor.We can have read-only properties also (use only get)
We also have auto-implemented properties
Properties with backing fields
One basic pattern for implementing a property involves using a private backing field for setting and retrieving the property value. The get
accessor returns the value of the private field, and the set
accessor may perform some data validation before assigning a value to the private field.
The following example illustrates this pattern:
Conversions & Validations
The get
accessor returns the value of the private field, and the set
accessor may perform some data validation before assigning a value to the private field. Both accessors may also perform some conversion or computation on the data before it's stored or returned.
The following example illustrates this pattern:
Auto-implemented properties
In some cases, property get
and set
accessors just assign a value to or retrieve a value from a backing field without including any extra logic. By using auto-implemented properties, you can simplify your code while having the C# compiler transparently provide the backing field for you.
The following example repeats the previous one, except that Name
and Price
are auto-implemented properties. The example also removes the parameterized constructor, so that SaleItem
objects are now initialized with a call to the parameterless constructor:
Last updated