Lesson 33 +10 XP

Properties

Properties

Properties are like smart fields: they pair a private backing field with controlled get and set accessors.

A basic property

class Person
{
  private string name;   // field

  public string Name     // property
  {
    get { return name; }
    set { name = value; }
  }
}
  • get returns the value.
  • set assigns a value (the incoming value is called value).

Using a property

Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);

Auto-implemented properties

When you don't need extra logic, C# writes the backing field for you:

class Person
{
  public string Name { get; set; }
}

This is the short form - the field is created automatically.

Why not just a public field?

Properties let you add validation and logic later without breaking the code that uses them:

public int Age
{
  get { return age; }
  set
  {
    if (value >= 0) age = value;
  }
}

Read-only and write-only

  • { get; } - read-only.
  • { set; } - write-only.
  • Auto-properties can't easily be private set unless you add private set.

TL;DR

  • Properties wrap private fields with get / set.
  • public string Name { get; set; } is the auto form.
  • They support validation and changing logic later.
  • Use get; only for read-only.