What is the difference between const and readonly in C#?
Quick answer
A const is a compile-time constant that must be assigned where it is declared, while a readonly field can be assigned at declaration or in the constructor, so its value can be decided at runtime.
const values are baked into the calling code at compile time and are implicitly static. They can only be primitive types, strings or null. If you change a const in a library, every project using it must be recompiled to see the new value.
readonly fields are normal fields that cannot be reassigned after the constructor finishes. They can hold any type, can differ per instance, and are read at runtime. Note that readonly makes the reference unchangeable, not the object it points to. For compile-time values that will never change (such as the number of days in a week) use const; otherwise prefer readonly.
public class Config
{
public const int MaxRetries = 3; // compile-time
public readonly DateTime CreatedAt; // runtime, per instance
public Config() { CreatedAt = DateTime.UtcNow; }
}