Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if property has attribute

Tags:

performance

c#

Given a property in a class, with attributes - what is the fastest way to determine if it contains a given attribute? For example:

    [IsNotNullable]     [IsPK]     [IsIdentity]     [SequenceNameAttribute("Id")]     public Int32 Id     {         get         {             return _Id;         }         set         {             _Id = value;         }     } 

What is the fastest method to determine that for example it has the "IsIdentity" attribute?

like image 743
Otávio Décio Avatar asked Jan 12 '10 17:01

Otávio Décio


People also ask

How do I find out if a property has an attribute?

The hasAttribute() returns a Boolean value that indicates if the element has the specified attribute. If the element contains an attribute, the hasAttribute() returns true; otherwise, it returns false .

How do you know if a class has a specific attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

What is an attribute C#?

Advertisements. An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc. in your program. You can add declarative information to a program by using an attribute.


2 Answers

If you are using .NET 3.5 you might try with Expression trees. It is safer than reflection:

class CustomAttribute : Attribute { }  class Program {     [Custom]     public int Id { get; set; }      static void Main()     {         Expression<Func<Program, int>> expression = p => p.Id;         var memberExpression = (MemberExpression)expression.Body;         bool hasCustomAttribute = memberExpression             .Member             .GetCustomAttributes(typeof(CustomAttribute), false).Length > 0;     } } 
like image 23
Darin Dimitrov Avatar answered Oct 17 '22 07:10

Darin Dimitrov


There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):

var t = typeof(YourClass); var pi = t.GetProperty("Id"); var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity)); 

If you need to retrieve attribute properties then

var t = typeof(YourClass); var pi = t.GetProperty("Id"); var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false); if (attr.Length > 0) {     // Use attr[0], you'll need foreach on attr if MultiUse is true } 
like image 84
Hans Passant Avatar answered Oct 17 '22 07:10

Hans Passant