Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force a subclass to declare a constant?

Tags:

c#

I want to force subclasses to define a constant value.

Like

const string SomeConstantEverySubclassMustDefine = "abc"; 

I need that because I need to have it tied to the Type, rather than to the instance and you can't override static Methods/Properties iirc.

I'd really like to have a compile-time check for those constants.

Let me explain in more detail:

Some classes in our Domain-Model are special, you can take certain actions for them, depending on the type. Thus the logic is tied to the type. The action to be taken requires a string tied to the type. I sure could create an instance everytime as a workaround and declare an abstract property, but that's not what I want. I want to enforce the declaration of the string at compile-time, just to be sure.

like image 874
Falcon Avatar asked Aug 13 '10 13:08

Falcon


1 Answers

No, you can't. I would suggest you make your base class abstract, with an abstract property which you can fetch when you want. Each child class can then implement the property just by returning a constant if it wants. The downside is that you can't use this within static methods in the base class - but those aren't associated with the child classes anyway.

(It also allows child classes to customise the property per instance as well, if necessary... but that's rarely an actual problem.)

If this doesn't do enough for you, you might want to consider a parallel type hierarchy. Basically polymorphism simply doesn't happen in a type-specific way in .NET; only in an instance-specific way.

If you still want to do this and fetch it with reflection, I suggest you just write unit tests to ensure that the relevant constants are defined. When you get beyond what the type system can describe, that's often the best you can do.

like image 124
Jon Skeet Avatar answered Oct 04 '22 03:10

Jon Skeet