Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Attribute Limit

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

like image 307
C. Ross Avatar asked Aug 08 '26 07:08

C. Ross


1 Answers

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.

like image 143
ShuggyCoUk Avatar answered Aug 09 '26 21:08

ShuggyCoUk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!