This subject is related to encapsulation principle, you can find more about it here.
Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Accessors
There are two basic types of accessors
set {accessor-body} get {accessor-body}
Set allows to assign value to the field, called write method. It uses variable key word that represents the value that is assigned.
Get allows to return the value of the field, read method. Get must return a value;
Field
Private field will prevent user from changing the data directly. This is concept of encapsulation. Field naming convention is to use underscore as prefix and start with low case letter.
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When you access it uses the underlying field, but only exposes
// the contract that will not be affected by the underlying field
public string MyProperty
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
}
Properties can be self implemented using
public int Number{ get; set; }
Properties Implementation
One of properties advantages is option of selecting which of read/write method will be available, for example we can want to restrict access to variable, making it read only. This will not allow user to change the data. To do this we write only get method in implementation.
Another advantage of properties is ability to perform operations on data inside the accessors. Let’s say we want to assign only positive numbers
using System;
class Example
{
int _id;
public int Id
{
get
{
return this._id;
}
set
// We don't allow this to be a negative value
if (value < 0 )
{
throw new Exception("Invalid number");
}
this._id = value;
}
}
}
Default Values
Automatic properties have support for default values much like fields.
public int Id { get; set; } = 404; // Has default value.
To conclude, Using properties is a vary good habit. It can protect the fields from corruption by setting checks conditions in setter. Or it can help with reading the value, using getter implementation. Using properties we can change the values of private field without exposing it, which is part of encapsulation principle. In next articles I’ll cover most important design patterns. Stay Awesome!