tags:

views:

100

answers:

2

Scenario: I have a base class "MyBase". I have a custom attribute "MyAttrib"

With that I do this:

[MyAttrib(1234)]
class MyClass : MyBase()
{
 MyClass()
 {
 }
}

Question: Can I in any way force classes inherting from MyBase to have the attribute MyAttrib?

+2  A: 

No, there is no way to have the compiler require an attribute in C#. You do have some other options available to you. You could write a unit test that reflects on all types in the assembly and checks for the attribute. But unfortunately there is no way to have the compiler force the usage of an attribute.

Andrew Hare
A: 

You could use PostSharp for this. Inherit your attribute class from the OnMethodInvocationAspect class (PostSharp), and override the CompileTimeValidate method.

A bit similar; albeit the other way around (I only wanted that a certain attribute could be applied to classes that implemented a specific interface): http://fgheysels.blogspot.com/2008/08/locking-system-with-aspect-oriented.html

Frederik Gheysels