A property in C# is a member of a
class that provides controlled access to a value. It looks like a
variable when you use it, but it’s backed by get and set accessors that control how the value is read and written.
Auto-Property#
The simplest form is the auto-property. The compiler generates the backing storage automatically.
public class Player
{
public int WinCount { get; set; }
}get— allows the value to be readset— allows the value to be written
Using it looks exactly like using a variable:
Player player = new Player();
player.WinCount = 0;
Console.WriteLine(player.WinCount);Read-Only Property#
Omit the set accessor to make a property read-only from outside the class.
public class Player
{
public int WinCount { get; private set; }
}private set means only code inside the class can change the value. Code outside can still read it.
Property with Initial Value#
You can give a property a default value directly in the declaration.
public class Player
{
public int WinCount { get; set; } = 0;
}Properties vs Fields#
A field is a plain variable on a class: public int WinCount;. A property is public int WinCount { get; set; }. They look similar but properties give you control — you can restrict access, add validation, or change the implementation later without touching the rest of the code.
In C#, the convention is to use properties for any value you intend to expose publicly, and fields only for internal implementation details.
Common Mistakes#
Forgetting the curly braces
public int WinCount get; set; is a compile error. The get and set accessors must be inside curly braces: public int WinCount { get; set; }.
Using a field when a property is expected Some C# features — data binding, serialisation, certain frameworks — work with properties but not fields. Starting with properties by default avoids these issues later.
Making everything public set by default
If a value should only change inside the class, use private set. Exposing set publicly means any code anywhere can change the value, which makes bugs harder to track down.
Resources#
- Properties (C# programming guide) (external link) — Microsoft Learn