5

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

1
  • As Mehrdad explained, you can't do that. Could you tell us why you want to restrict attributes in such a way? Could you tell us your usecase? Jul 8, 2009 at 23:53

3 Answers 3

8

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 { 
}
5

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;
    }
}
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy