Properties
Encapsulate state with auto, computed, validated, and init-only properties.
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
LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Generics
Write type-parameterized methods and classes with constraints.
Delegates and Events
Define delegate types and publish events with safe subscription.
Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.
Collections
Use List, Dictionary, HashSet, Queue, Stack, and read-only views.