Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple AttributeTargets in AttributeUsage

[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
...
}

I want this custom attribute used both on properties and fileds but not others. How do I assign multiple targets(AttributeTargets.Property and AttributeTargets.Field)? Or It's just not possible?

And AttributeTargets.All is not what I want.

like image 439
Sean C. Avatar asked Dec 02 '14 02:12

Sean C.


1 Answers

You can specify multiple targets like this, by using the | (bitwise OR) operator to specify multiple enum values:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MyAttribute : Attribute
{
    ...
}

The bitwise OR operator works with the AttributeTargets enum because its values are assigned a particular way and it's marked with the Flags attribute.

If you care to, you can read more here:

  • C# Fundamentals: Combining Enum Values with Bit-Flags
  • Understand how bitwise operators work (C# and VB.NET examples)
like image 65
Grant Winney Avatar answered Oct 24 '22 10:10

Grant Winney