C# Properties

Properties give you the safety of private fields with the convenience of public access. They look like fields when you use them, but behind the scenes they run get and set code that you control. This lesson shows how properties help you protect your data while keeping your code clean and simple.

The problem properties solve

You already know that making a field private protects it, but then no outside code can read or change it. The old fix was to write separate GetX and SetX methods for every field. Properties are C#'s built-in, tidier answer: they act as a controlled gateway to a private field.

A property with get and set

class Person
{
  private string name;   // the private backing field

  public string Name     // the property
  {
    get { return name; }
    set { name = value; }
  }
}

class Program
{
  static void Main()
  {
    Person p = new Person();
    p.Name = "Liam";              // calls set, value is "Liam"
    Console.WriteLine(p.Name);    // calls get, prints Liam
  }
}

The get accessor runs when you read the property, and the set accessor runs when you assign to it. Inside set, the special keyword value holds whatever was assigned on the right side of the equals sign.

Auto-implemented properties

When your get and set do nothing more than read and write a field, C# lets you skip the backing field entirely. This short form is called an auto-implemented property, and the compiler creates the hidden field for you.

The short auto-property form

class Person
{
  public string Name { get; set; }        // read and write
  public int Age { get; set; }
  public string Country { get; private set; } = "Unknown";  // read anywhere, write only inside
}

class Program
{
  static void Main()
  {
    Person p = new Person();
    p.Name = "Ava";
    p.Age = 30;
    Console.WriteLine($"{p.Name}, {p.Age}, {p.Country}");
  }
}
Note: You can control access on each accessor separately. Writing { get; private set; } lets any code read the value but only the class itself change it, which is great for values that should not be edited from outside.

Adding logic inside a property

  • Validate a value before storing it, such as rejecting negative ages
  • Convert or format data as it comes in or goes out
  • Make a property read-only by giving it only a get
  • Trigger other actions, like logging, when a value changes

Property styles at a glance

StyleLooks likeUse when
Full propertyget { } set { }You need custom logic or validation
Auto-property{ get; set; }You just need simple storage
Read-only{ get; }The value should never change after construction

Properties are the standard way to expose data in C#. Reach for a simple auto-property first, and upgrade it to a full property only when you actually need to run code on get or set.

Exercise: C# Properties

What is the main purpose of a property in C#?