In your example, this makes the properties read-only, but there are other uses.
public string Text { get { return _text; } }
If you want to perform some operation inside return_text and then return it against proeperty Text , you could be something like.
public string Text { get { return _text.ToUpper(); } }
This field is Encapsulation
Encapsulation is sometimes referred to as the first column or principle of object-oriented programming. According to the encapsulation principle, a class or structure can indicate how accessible each of its members should encode outside the class or structure. Methods and variables that are not intended to be used outside the class or the assembly can be hidden to limit the potential for coding errors or malicious exploits.
Consider the following example:
// private field private DateTime date; // Public property exposes date field safely. public DateTime Date { get { return date; } set { // Set some reasonable boundaries for likely birth dates. if (value.Year > 1900 && value.Year <= DateTime.Today.Year) { date = value; } else throw new ArgumentOutOfRangeException(); } }
In this example, there is a private date field that is openly open through the date property. Now, if you want to set the border for the date, you can see the set part of the property.
Habib
source share