What is the get-set property?

Fields within classes should generally be private and only allow access when needed. This is where the get-set property accessors, get or set, are used to access or change data. The get-set properties combine aspects of both fields and methods.

Syntax

private string myProperty; // Declare a private field
public string MyProperty // Property is Public: it can be accessed from outside the class
{
  get { return myProperty; } // Get retrieves the value from myProperty and returns it
  set { myProperty = value; } // Set gives access to change private field myProperty 
}

The get section of MyProperty can return the private field value of myProperty, and the set section can assign a value to the private field, myProperty. It’s common to name the private field the same name as the property except with a lowercase letter or with an underscore and then a lowercase letter, for example, _myProperty.

Get hands-on with 1200+ tech skills courses.