Search code examples
c#.net-2.0attributes

C# Attribute Limit


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


Solution

  • 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.