Search code examples
c#.netc#-3.0initializationreadonly

Why can't I initialize readonly variables in a initializer?


Why can't I initialize readonly variables in a initializer? The following doesn't work as it should:

class Foo
{
    public readonly int bar;
}

new Foo { bar=0; }; // does not work

Is this due to some technical limits of the CLR?

EDIT

I know that new Foo { bar=0; } is the same as new Foo().bar=0;, but is "readonly" enforced by the CLR, or is it just a compiler limitation?


Solution

  • C# 9.0 finally brings us init-only property setters:

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init

    struct Point
    {
        public int X { get; init; }
        public int Y { get; init; }
    }
    
    var p = new Point() { X = 42, Y = 13 };