Search⌘ K
AI Features

Get-Set Properties

Explore how get-set properties in C# provide controlled access to private class fields. Learn to implement custom logic, use auto-implemented properties, and restrict access with read-only or private setters to manage data effectively within your classes.

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
...