Roadmap › C# Language — Basics to Advanced › Module: Types in Depth
Lessons in this course (38)
20. Properties, indexers, static and const vs readonly
IntermediateMediumLesson 20 of 38
csharp
public class Account
{
private decimal _balance;
public decimal Balance { get => _balance; private set => _balance = value >= 0 ? value : throw new ArgumentException(); }
public string Owner { get; init; } = ""; // settable only during initialisation
public static int Count { get; private set; } // shared by all instances
public string Tier { get; set { field = value.Trim(); } } = ""; // C# 14 'field' keyword
public decimal this[int month] => _history[month]; // indexer
private readonly decimal[] _history = new decimal[12];
}const | readonly | static readonly |
|---|---|---|
| Compile-time constant, implicitly static | Per instance, set in declaration or constructor | One per type, set at runtime once |
| Only primitives/strings | Any type | Any type |
| Value is copied into calling assemblies — changing it requires recompiling callers | Read at runtime | Read at runtime |