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}}
Line 2: Properties usually have public access to expose data, while the underlying fields remain private.
Lines 4–12: The property body contains
getandsetaccessors, 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.
Line 1: Uses a file-scoped namespace to reduce indentation.
Line 6: Initializes the
modelfield tostring.Emptyto ensure safety, as modern C# does not allow null references by default.Lines 9–13: Defines the
Modelproperty, which reads from and writes to themodelbacking field.Lines 19–23: Defines the
Priceproperty, managing access to thepricefield.
Let’s use Program.cs to execute it.
Line 3: Creates a new instance of the
Carclass.Line 4: The assignment triggers the
setblock of theModelproperty.Line 7: ...