Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a class is decorated with a specific attribute

I'm trying to determine if a interface is decorated with a specific attribute. For example, I have the following interface:

<MyCustomAttribute()> _
Public Interface IMyInterface
    Function Function1
    Sub DeleteWorkflowInstanceMap(ByVal instanceId As Guid)
    Sub InsertWorkflowInstanceMap(ByVal instanceId As Guid, ByVal aliasName As String)
End Interface

How do I determine if IMyInterface is decorated with the MyCustomAttribute attribute?

like image 611
Matt Ruwe Avatar asked Feb 10 '10 17:02

Matt Ruwe


People also ask

How would you determine if a class has a particular attribute in C#?

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

What are attributes and reflections in C#?

Attribute ReflectionReflection is a set of . NET APIs that facilitate retrieving metadata from C# attributes. Reflection is used to retrieve attributes associated with an attribute target. This code calls GetCustomAttributes to list the attribute type names for the Id property.


2 Answers

Even better than GetCustomAttributes is the Shared method IsDefined:

Attribute.IsDefined(GetType(IMyInterface), GetType(MyCustomAttribute))
like image 112
Marcel Gosselin Avatar answered Oct 15 '22 20:10

Marcel Gosselin


GetType(IMyInterface).GetCustomAttributes(GetType(MyCustomAttribute), false).Length > 0

(I hope I have the VB syntax right.) Basically get a Type representing IMyInterface, then call GetCustomAttributes on it passing the type of attribute you're interested in. If that returns a non-empty array, the attribute is present.

like image 30
itowlson Avatar answered Oct 15 '22 19:10

itowlson