Is it possible to limit the number of properties that an attribute is applied to in a particular class?
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.
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.
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.