(C#) Making custom attributes required at compile-time
Hi,
I'd like to make a custom attribute required at compile-time basically it is a custom attribute that sits on a class.
I have an abstract class called ScreenControl, and I want every subclass of ScreenControl to have to provide this custom attribute on its class definition.
My current solution only works at run-time - which is to have an assertation that 'this.getType()' provides the desired custom attribute in the ScreenControl constructor. Is there a way to make it a compile-time error(/warning) not to provide the custom attribute on types deriving from my class? and at compile time?
No, you don't have that kind of control. Those kinds of requirements are enforced by the compiler or the runtime, neither of which you can modify.
Quote:Original post by Timberl
I have an abstract class called ScreenControl, and I want every subclass of ScreenControl to have to provide this custom attribute on its class definition.
As Arild said, there's no way to enforce a "contract" for attributes. But if you want every subclass of ScreenControl to provide a certain functionality, that's what virtual methods are for. You don't need to use attributes.
Quote:Original post by kSquaredQuote:Original post by Timberl
I have an abstract class called ScreenControl, and I want every subclass of ScreenControl to have to provide this custom attribute on its class definition.
As Arild said, there's no way to enforce a "contract" for attributes. But if you want every subclass of ScreenControl to provide a certain functionality, that's what virtual methods are for. You don't need to use attributes.
But I really need it available from the class without an instance
if I make it static then I can't have it in the superclass (at least I cant override it in subclasses) attributes seemed the most logical way of doing it
You could make a separate application that checks (using reflection) whether all necessary attributes are present and have it called as a post-build step.
I'm not a C# person, but would the C# equivalent of the following C++ do what you require?:
Enigma
class Base{ public: Base(CustomAttribute & customAttribute) { if (!customAttribute_) { customAttribute_ = &customAttribute; } } // pure virtual member functions protected: static CustomAttribute * customAttribute_;};CustomAttribute Base::customAttribute_ = null;class Derived{ public: Derived() : Base(derivedCustomAttribute_) { } private: static CustomAttribute derivedCustomAttribute_;};
Enigma
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement