C# Properties and Fields

Updated: 30 January 2023

Properties enable a class to expose a public way of getting and setting values. Properties are special methods called accessors. A property is a member which can read, write or compute a private field.

The basic pattern involves a private backing field. Both get and set accessors may perform some conversion or computation on the data before it’s stored or returned.

public class TimePeriod
{
    private double _seconds;

    public double Hours
    {
        get { return _seconds / 3600; }
        set
        {
            if (value < 0 || value > 24)
                throw new ArgumentOutOfRangeException(nameof(value),
                      "The valid range is between 0 and 24.");

            _seconds = value * 3600;
        }
    }
}

Useage

TimePeriod t = new TimePeriod();
// The property assignment causes the 'set' accessor to be called.
t.Hours = 24;

// Retrieving the property causes the 'get' accessor to be called.
Console.WriteLine($"Time in hours: {t.Hours}");

More succinctly with expression bodies

public class SaleItem
{
    string _name;
    decimal _cost;

    public SaleItem(string name, decimal cost)
    {
        _name = name;
        _cost = cost;
    }

    public string Name
    {
        get => _name;
        set => _name = value;
    }

    public decimal Price
    {
        get => _cost;
        set => _cost = value;
    }
}

Auto-implemented properties

In some cases, property get and set accessors just assign/retrieve a value from a backing field without extra logic. By using auto-implemented properties, the C# compiler transparently provides the backing fields.

public class SaleItem
{
    public string Name
    { get; set; }

    public decimal Price
    { get; set; }
}

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties

Leave a comment