Tuesday, March 15, 2011

Overriding constants in derived classes in C#

In C# can a constant be overridden in a derived class? I have a group of classes that are all the same bar some constant values, so I'd like to create a base class that defines all the methods and then just set the relevant constants in the derived classes. Is this possible?

I'd rather not just pass in these values to each object's constructor as I would like the added type-safety of multiple classes (since it never makes sense for two objects with different constants to interact).

From stackoverflow
  • Unfortunately constants cannot be overridden as they are not virtual members. Constant identifiers in your code are replaced with their literal values by the compiler at compile time.

    I would suggest you try to use an abstract or virtual property for what you would like to do. Those are virtual and as such can (must, in the case of an abstract property) be overridden in the derived type.

  • it's not a constant if you want to override it ;) try a virtual property with an protected setter...

    
    public class MyClass {
        public virtual MyConst { get {return "SOMETHING"; }}
    }
    ...
    public class MyDerived : MyClass {
        public virtual MyConst { get { return "SOMETHINGELSE"; }}
    }
    

0 comments:

Post a Comment