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
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?
Most helpful comment
I think the compiler behaviour is correct. static readonly property can only be assigned in static constructor