Reputation: 3134
When I inherit from a base class, Visual Studio (v2008 here) informs me about all MustInherit members that need to be created in the derived class, which is very handy.
However, I also want my derived class to define some shared members - the values of which will be different for each derived class. Unfortunately, .NET doesn't allow MustInherit on shared members in a base class.
Is there any other way of getting Visual Studio to remind me that my derived class should also include certain specific shared members?
Upvotes: 1
Views: 145
Reputation: 1675
It sounds like you are trying to use polymorphy on a class level which won't work.
int result = ParentClass.STATIC_VALUE;
int result2 = ChildClass.STATIC_VALUE;
int result3 = AnotherChildClass.STATIC_VALUE;
Assume STATIC_VALUE is set to different values. How do you want .Net to pick the "right" value as there is no instance tied to either of this three classes?
ParentClass will always have it's defined value and never a value of a base class. ChildClass will have either ParentClass's value, or - if defined - it's own value which shadows ParentClass's value.
In order to retrieve the value of the inheriting class you alway have to call this class explicitly. There is no way to use a polymorpic behavior.
In .NET, can a base class somehow ensure derived classes define shared members?
It will be defined automatically, but you cannot ensure that another programmer dealing with your base class later has to define its own value. You should reconsider if your problem can be solved by using class members or properties.
Upvotes: 0
Reputation: 1500903
No, there's no way of doing this - and it sounds like a design smell, to be honest.
Half the point of having MustInherit
members is that you can then access them from the code in the base class. That wouldn't be appropriate for Shared
members, as there'd be no indication of which class to access the shared members of.
You haven't given us any context to explain why you want to do this, but I suggest you try to look for a different design. Sometimes having parallel inheritance hierarchies (e.g. one for "factories" and one for instances) can be useful, for example - then the members you might otherwise make Shared
would be instance members within the factory types. It really does depend on what you're trying to achieve though.
Upvotes: 1