Skary Skary - 1 year ago 96
C# Question

Constraint Attribute to property of given type

As stated in the title i would like to know if there is a way to constraint attribute so that you get compile time error if you apply an attribute to a wrong property or to a method (i would like that these attributes will apply only to property).

Eg :

public string MyStringPropery { get; set; } //<-- ok pass compile time constraint

public int MyIntProperty { get; set; } //<-- throw error at compile time for type missmatch (that attribute will apply only to string not int)

public string SayHello () //<-- throw error at compile time, that attribute apply only to property not method
return "Hello!" ;

Optionally will be nice if i can constraint my attribute so that they can be used only inside a class that implement specific interface (or inherits form a specific base class).

Answer Source

Checking the type of your property can not be done at compile time since you don't have access to the member you attach the attribute to. Also, the compiler will not actually instantiate your attribute or run code on it. It will merely add it to the assembly metadata. The compiler runs its built-in checks, which you can't extend.

But restricting to properties can be done in your attribute definition:

public class StringAttribute : Attribute
    //Attribute definition
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download