C# – Abstract classes and constants

abstract classcclass-design

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.

Best Answer

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.