LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2915 min read

Properties

Learn C# properties, auto-implemented properties, and get/set accessors.

What is a Property?

A property looks like a public field from the outside but is backed by get/set methods (accessors) internally. This lets you add validation or logic later without breaking any code that uses the property.

Auto-Implemented Properties

When you don't need custom logic, C# lets you skip writing a backing field manually.

class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
var person = new Person { Name = "Meera", Age = 30 };
Console.WriteLine($"{person.Name}, {person.Age}");

Custom get/set Logic

class Product
{
private decimal price;
public decimal Price
{
get => price;
set
{
if (value < 0) throw new ArgumentException("Price can't be negative.");
price = value;
}
}
}
var product = new Product();
product.Price = 49.99m; // runs through the validation in set
Console.WriteLine(product.Price);
Output

Click Run to see what this code prints.

Read-Only Properties

A property with only a `get` accessor (or `init` since C# 9, settable only during object initialization) can't be changed after the object is created.

class Order
{
public string Id { get; }
public Order(string id)
{
Id = id; // allowed only in the constructor
}
}

FAQs

Generally, prefer properties for anything public — they give you room to add validation later without a breaking change to your class's public API.

Summary

  • Properties expose controlled access to a class's data.
  • Auto-implemented properties skip writing a backing field manually.
  • Custom get/set logic lets you validate values on assignment.
Next Lesson →

Enums