[Solved] Overriding Static Constants in Derived Classes in C#


What you’re looking for is a bit strange, but one option to keep them static and provide new value/implementation is to just hide the inherited members, by simply using the same name:

public abstract class Effect
{
    public const float duration = 1.0f;

    public static void boo()
    {
        // this prints 1.0f
        Console.WriteLine(duration);
    }
}

public class EffectA : Effect
{
    public new const float duration = 3.0f;

    public new static void boo()
    {
        // this prints 3.0f
        Console.WriteLine(duration);
    }
}

Note the new keyword just gets rid of the compiler warning for you, using the same name is what results in hiding.

Update

Based on your comment, here’s how you can avoid duplication and just call the shared implementation:

public abstract class Effect
{
    public const float duration = 1.0f;

    public static void boo(float val = duration)
    {
        // your complex shared implementation
        Console.WriteLine(val);
    }
}

public class EffectA : Effect
{
    public new const float duration = 3.0f;

    public new static void boo()
    {
        Effect.boo(duration);
    }
}

4

solved Overriding Static Constants in Derived Classes in C#