2
votes
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

2

2 Answers

4
votes

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.

3
votes

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; }
    }
}