Skary Skary - 12 days ago 7
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 :

[StringAttribute(..something)]
public string MyStringPropery { get; set; } //<-- ok pass compile time constraint

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

[StringAttribute(..something)]
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

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:

[AttributeUsage(AttributeTargets.Property)]
public class StringAttribute : Attribute
{
    //Attribute definition
}