views:

277

answers:

5
+1  Q: 

C# Attribute Limit

Is it possible to limit the number of properties that an attribute is applied to in a particular class?

+1  A: 

No. Why do you want to do this?

John Saunders
A: 

No, I doubt it.

Mehrdad Afshari
+1  A: 

I do not think it is possible at compile time. But you could add some code to the instance constructors or to a static constructor that checks this via reflection at run time.

Daniel Brückner
+3  A: 

At compile time no.

At runtime you could validate this via a static initialiser which throws if this invariant is violated though this would be considered very poor style it would be safe in the sense that no code could execute while the invariant doesn't hold.

If you think about the extensibility inherent in .Net even if you could verify this at compile time imagine:

compile dll A with

public class Foo 
{
     public int Property1 {get;}
}

compile dll B referencing A.dll with class

public class Bar
{
     [OnlyOneAllowedOnAnyPropertiesPerClass]
     public int Property2 {get;}
}

then you recompile A.dll with

public class Foo 
{
     [OnlyOneAllowedOnAnyPropertiesPerClass]
     public int Property1 {get;}
}

And attempt to run this new A.dll with the old B.dll (they are binary compatible in all other respects so this is fine)

Clearly the runtime would have to do considerable effort sanity checking this, not to mention B might not be loaded for some time suddenly Making either one or both of A and B 'illegal'.

Therefore you should not expect this to ever be functionality available in the framework.

ShuggyCoUk
+1  A: 

If it's important in (or right after) compile time, you should create an FxCop rule or a custom search for your attribute (pattern like [OnlyOnceAttribute]).

findstr "[OnlyOnceAttribute]" *.cs

The findstr utility returns the matched lines. You need only a batch file that catch line count and get back an error to the caller (=MSBuild Task), and the build fail.

boj
nice idea but note that partial classes and inheritance will both subvert this and multiple classes in a file would cause false positives.Going to a proper FxCop rule would work so long as you have access to the total code base in compiled form.
ShuggyCoUk