tags:

views:

132

answers:

3

Hi

Is it possible to restrict an attribute usage to just protected and public variables. I just want to restrict to private variables.

+5  A: 

No, you can't do that. You can restrict attribute usage only based on the type of the target, not anything else.

[AttributeUsage(AttributeTargets.Method)]
public class MethodOnlyAttribute : Attribute { 
}
Mehrdad Afshari
+3  A: 

To the best of my knowledge, you cannot. The AttributeTargets enumeration lists which application elements you can constrain attribute usage to.

Steve Guidi
A: 

You can do this with PostSharp, here's an example of a field which can only be applied to a public or protected field:

[Serializable]
[AttributeUsage(AttributeTargets.Field)]
public class MyAttribute : OnFieldAccessAspect
{
    public override bool CompileTimeValidate(System.Reflection.FieldInfo field)
    {
        if (field.IsPublic || field.IsFamily)
        {
            throw new Exception("Attribute can only be applied to Public or Protected fields");
        }

        return true;
    }
}
theburningmonk