How to override constants derived classes?

You should use the new keyword to explicitly hide the inherited member:

public class A
{
    public const int beingSupportedRate = 0;
}

public class B : A
{
    public new const int beingSupportedRate = 1;
}

Remember that you cannot access the constant member from an instance.

Console.WriteLine(A.beingSupportedRate);
Console.WriteLine(B.beingSupportedRate);

Output:

0
1

There are some problems that you should consider when using this solution. Take the following console program, for example:

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();

        a.GetBeingSupportRate();
        b.GetBeingSupportRate();
        c.GetBeingSupportRate();

        Console.Read();
    }

    public class A
    {
        public const int beingSupportedRate = 0;
        public void GetBeingSupportRate()
        {
            Console.WriteLine(beingSupportedRate);
        }
    }

    public class B : A
    {
        public new const int beingSupportedRate = 1;

    }

    public class C : B
    {

    }
}

This will output 0 for all three class instances, since the inherited method uses the constant value in A. This means you will have to override all methods that reference the constant.

A preferred approach is to use an interface with a property that must be implemented and not use constants for this purpose.


Fields (including constants) can't be virtual. That has nothing to do with it being a constant... it's just the way fields work... although the fact that constants are implicitly static makes it even less feasible, as it were.

If you want polymorphic behaviour, it has to be via an instance member which is a property, method or event.

As an aside, I strongly suspect your "I want it as const for performance reasons" justification is bogus micro-optimization. It's not even clear how you're using this, but I very much doubt that you've tried it as a non-constant and proved that it's too slow.


Constants cannot be overridden, they are constant.

If you want this value to be alterable by extension then you'll need to use something less constant, with a nature of being changed per context, such as an abstract element to implement or virtual to override.

Tags:

C#