mpen
mpen

Reputation: 282895

Static readonly field cannot be assigned to (except in static constructor)

abstract class DirectiveNode
{
    public static readonly RequirementOptions ArgumentOptions = RequirementOptions.Optional;
}

class IfNode : DirectiveNode
{
    static IfNode()
    {
        ArgumentOptions = RequirementOptions.Required; // error here
    }

I don't understand the problem. I thought static IfNode() was a static constructor? Why the error?


Just found this: Assigning to static readonly field of base class

Upvotes: 3

Views: 9868

Answers (2)

dahlbyk
dahlbyk

Reputation: 77540

Unlike nonstatic constructors, a subclass's static constructor has no relationship with the parent static constructor. If you want the subclass to be able to change the ArgumentOptions value used by base class functions, consider a virtual property:

abstract class DirectiveNode
{
    public virtual RequirementOptions ArgumentOptions
    {
        get { return RequirementOptions.Optional; }
    }
}

class IfNode : DirectiveNode
{
    public override RequirementOptions ArgumentOptions
    {
        get { return RequirementOptions.Required; }
    }
}

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422026

You can only assign it in the static constructor of the same class.

By the way, it sounds like you expect the static field to contain different values depending on which derived class you are talking about. This is not how it works. Only a single instance of the field will exist and it's shared across all derived classes.

Upvotes: 4

Related Questions