Search⌘ K
AI Features

Properties

Explore how to create and use properties in C#, focusing on get and set accessors to control access to private fields. Understand validation within setters, use of access modifiers for encapsulation, auto-implemented properties for concise code, and modern features like init accessors and required modifiers to enforce initialization rules.

In C#, properties are special class members that provide a flexible mechanism to read, write, or compute the value of a private field.

Define a property

Properties are created with the following syntax:

// Like other members, properties can have access modifiers
[access modifiers] property_type property_name
{
get
{
// Get block contains actions to perform when returning the value of the field
}
set
{
// Set block contains actions to perform when setting the value of the field
}
}
General syntax for defining a property in C#
  • Line 2: Properties usually have public access to expose data, while the underlying fields remain private.

  • Lines 4–12: The property body contains get and set accessors, which act as methods for reading and writing data.

Properties do not store data directly. Instead, they act as intermediaries between external code and the data stored in fields.

Let’s look at the following example. Here, the Car class defines the private model and price fields that store the model and the price of the car. Along with these fields, there are two public properties called Model and Price.

C# 14.0
namespace Properties;
public class Car
{
// model field
private string model = string.Empty;
// Model property
public string Model
{
get { return model; }
set { model = value; }
}
// price field
private decimal price;
// Price property
public decimal Price
{
get { return price; }
set { price = value; }
}
}
  • Line 1: Uses a file-scoped namespace to reduce indentation.

  • Line 6: Initializes the model field to string.Empty to ensure safety, as modern C# does not allow null references by default.

  • Lines 9–13: Defines the Model property, which reads from and writes to the model backing field.

  • Lines 19–23: Defines the Price property, managing access to the price field.

Let’s use Program.cs to execute it.

C# 14.0
using Properties;
Car car = new Car();
car.Model = "Lexus LS 460 L";
car.Price = 65000;
Console.Write($"{car.Model} costs {car.Price} dollars");
  • Line 3: Creates a new instance of the Car class.

  • Line 4: The assignment triggers the set block of the Model property.

  • Line 7: ...