vijai
vijai

Reputation:

Restricting Attribute usages only for Public and Protected Variables c#

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

Upvotes: 5

Views: 1602

Answers (3)

theburningmonk
theburningmonk

Reputation: 16051

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

Upvotes: 5

Steve Guidi
Steve Guidi

Reputation: 20200

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

Upvotes: 4

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

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

Upvotes: 8

Related Questions