Skip to content
C#

Properties

Encapsulate state with auto, computed, validated, and init-only properties.

By EZ4Code Team
propertiesencapsulation

Code

using System;

public class Temperature
{
    private double _celsius;

    // Auto-implemented property
    public string Unit { get; set; } = "C";

    // Full property with validation
    public double Celsius
    {
        get => _celsius;
        set => _celsius = value < -273.15
            ? throw new ArgumentOutOfRangeException(nameof(value))
            : value;
    }

    // Computed read-only property
    public double Fahrenheit => _celsius * 9 / 5 + 32;

    // Init-only setter
    public string Sensor { get; init; } = "default";

    public Temperature(double celsius) => Celsius = celsius;
}

var t = new Temperature(25) { Sensor = "A1" };
Console.WriteLine($"{t.Celsius:F1} C = {t.Fahrenheit:F1} F");
t.Celsius = 100;
Console.WriteLine($"{t.Celsius:F1} C = {t.Fahrenheit:F1} F");

Explanation

Properties expose state through get and set accessors that can validate, compute, or wrap a private field. Auto-implemented properties auto-generate the backing field for simple cases. Init-only setters allow assignment during object construction but freeze afterwards, supporting immutable initialization patterns.

More C# Snippets