Sobes.tech
Junior

В чем разница между ReadOnly и const в C#?

sobes.tech AI

Answer from AI

Characteristic const readonly
Initialization Time During compilation. The value must be known at compile time. During runtime. Can be set in the constructor or at declaration.
Data Types Only primitive types, string, enum. Any data types.
Scope Only static fields. Can be an instance (non-static) or static field.
Mutability Cannot be changed after initialization. Cannot be changed after constructor completion (for instance fields) or after the first access (for static fields).
public class MyClass
{
    const int CompileTimeConstant = 10; // Value must be known at compile time.
    readonly int RuntimeConstant; // Can be set in the constructor.
    static readonly int StaticRuntimeConstant; // Can be set in the static constructor.

    public MyClass(int value)
    {
        RuntimeConstant = value; // Initialization in the instance constructor.
    }

    static MyClass()
    {
        StaticRuntimeConstant = DateTime.Now.Year; // Initialization in the static constructor.
    }

    public void PrintValues()
    {
        Console.WriteLine($"CompileTimeConstant: {CompileTimeConstant}");
        Console.WriteLine($"RuntimeConstant: {RuntimeConstant}");
        Console.WriteLine($"StaticRuntimeConstant: {StaticRuntimeConstant}");
    }

    public static void SomeStaticMethod()
    {
        //CompileTimeConstant = 20; // Compilation error: cannot change const.
        //StaticRuntimeConstant = 2023; // Compilation error: cannot change static readonly after initialization.
    }
}