I have two classes that share a lot of code and are conceptually variations on a common class. So I want an abstract class that contains all their common code and then they can each inherit from it and fill in the stuff unique to them. However I am running into a problem with constants and static methods. Basically, the relationship I have is like this:

Class A and Class B both have some methods that don't depend on an instance of the class, just the value of a set of constant strings. Basically as such:

const string onePrefix;
const string differentPrefix;

static string ConvertMethod(string input)
  input.replace(onePrefix, differentPrefix);

The method code is the same between the two classes, so I would like to have it in the abstract class. But the actual values of the two constants are different between the two classes. But abstract constants are not a thing you can do as far as I can tell so I'm not sure how to go about structuring my classes to make this work like I want it to. I've considered just not having the values be constants, but they are used in my constructors before an instanced object is created.

2 Answers 2


It's a bit of a code smell to me that you have a constant that you want to share polymorphically between two classes so that they can define it on their own.

Constants by design have been made to be unaffected by polymorphism so I would suggest you turn that into an abstract property in your abstract base class.

You could either do that or have a concrete class as your supertype. Then inherit all the common functionality from your concrete class while having your constants defined on each subclass which you can access when you new them up.


Try a readonly variable. MSDN says this:

The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants, as in this line: public static readonly uint l1 = (uint)DateTime.Now.Ticks;

  • If the suggestion here is be to change onePrefix and differentPrefix to readonly properties in the abstract class and then to set the values of those properties in the constructors of the implementing classes by passing them down to the constructor of the abstract class, I agree. May 4, 2022 at 22:33
  • 1
    Well, yeah. And in "the covering all bases" department, keep two differently-named constants in the abstract class to be used for default values of constructor optional parameters.
    – radarbob
    May 4, 2022 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.