Search code examples
c#custom-attributes

Force the usage of an attribute on properties, if they already have another attribute


I want to force the usage of an attribute, if another attribute is used. If a special 3rd party attribute is attached to a property, this attribute also needs to be given to a property. Is there any possibility of doing this?

For example:

[Some3rdPartyAttribute("...")]
[RequiredAttribute("...)]
public bool Example{get; set;}

should bring no compile error,

[Some3rdPartyAttribute("...")]
public bool Example{get; set;}

should bring a compile error or warning.

The attribute itself is definded like the example from http://msdn.microsoft.com/en-US/library/z919e8tw(v=vs.80).aspx itself . But how to force the usage of the attribute if another attribute is used?


Solution

  • Another option is using some AOP techniques. Like for example:

    PostSharp.

    Using it you can at compilation analyze yur code and emit a error if some condition does not sutisfies your requirements.

    For concrete example on attributes, can have a look on :

    PostSharp 2.1: Reflecting Custom Attributes