Properties inside classes in C#

 A property is a class member that exposees the class's private fields.

  • Internally, C# properties are special methods called accessors
  • It has two accessors, a get property accessor or a getter and a set property accessor or a setter.
  • C# properties can be read-only or they can be write-only and they can be both readable and writeable both
  • We can have logic white setting values in C#
Example: 
class Person
{
  private string name; // field

  public string Name   // property
  {
    get { return name; }   // get method, can also have logic before returning the value
    set { name = value + 1; }  // set method, logic is there before setting the value
  }
}

Properties and Encapsulation

Before we start to explain properties, you should have a basic understanding of "Encapsulation".

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must:

  • declare fields/variables as private
  • provide public get and set methods, through properties, to access and update the value of a private field

Comments