Roslyn: static readonly autoimplemented property

Created on 20 Jan 2017  路  4Comments  路  Source: dotnet/roslyn

Why does the following code given an error during compilation?
public class A { }

public class B
{
    private static A AF { get; }

    public B()
    {
        AF = new A();
    }
}

C# 6.0, .NET 4.5, VS2015 Update 3

Expected Behavior:
This code should not give a compiler error

Actual Behavior:
error CS0200: Property or indexer 'B.AF' cannot be assigned to -- it is read only

Area-Compilers Bug Concept-Diagnostic Clarity help wanted

Most helpful comment

I think the compiler behaviour is correct. static readonly property can only be assigned in static constructor

All 4 comments

I think the compiler behaviour is correct. static readonly property can only be assigned in static constructor

As @stepanbenes says, you are trying to initialise a static readonly field via an instance constructor. Static readonly fields can only be initialised via static constructors. So correcting your code to the following, results in it compiling properly:
````cs
public class A { }

public class B
{
private static A AF { get; }

static B()
{
    AF = new A();
}

}
````

Alternatively, mark setter as private or in this case just write setter down.

If that is what you want to really do... but in most cases assigning value to static property from instance constructor would seem as malpractice.

Oh Ok. A point to consider. Can the error message be improved?

Was this page helpful?
0 / 5 - 0 ratings