How do properties with get and set work in C#?

← .NET and C# answers

A property exposes a value through get and set accessors. Use auto-properties (public string Name { get; set; }) for simple data and a backing field when the setter needs logic.

public class Account
{
    // Auto-property: the compiler creates the backing field
    public string Owner { get; set; } = "";
 
    // Read-only from outside, settable inside the class
    public decimal Balance { get; private set; }
 
    // Set once, at creation (C# 9+)
    public Guid Id { get; init; } = Guid.NewGuid();
 
    // Custom logic with a backing field
    private string _email = "";
    public string Email
    {
        get => _email;
        set => _email = value?.Trim() ?? throw new ArgumentNullException(nameof(value));
    }
 
    // Computed, no storage
    public bool IsOverdrawn => Balance < 0;
}
 
var a = new Account { Owner = "Ada", Id = Guid.NewGuid() };

Prefer properties over public fields: they can add validation or change storage later without changing the callers. The implicit parameter value in a setter holds what the caller assigned.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required