Is there an advantage to using IsDefined over GetCustomAttributes

Consider the case when the assembly contains one or more types associated with the MyAttribute user attribute, and you need to get a list of these types. Is there any benefit to using IsDefined against GetCustomAttributes besides a more compact syntax? To show / hide what the other does not have? Is more effective than the other?

Here is a sample code demonstrating each use:

 Assembly assembly = ... var typesWithMyAttributeFromIsDefined = from type in assembly.GetTypes() where type.IsDefined(typeof(MyAttribute), false) select type; var typesWithMyAttributeFromGetCustomAttributes = from type in assembly.GetTypes() let attributes = type.GetCustomAttributes(typeof(MyAttribute), false) where attributes != null && attributes.Length > 0 select type; 
+4
reflection c # attributes
source share
2 answers

A quick quick test with two methods, and it seems that IsDefined much faster than GetCustomAttributes

200,000 iterations

 IsDefined average Ticks = 54 GetCustomAttributes average Ticks = 114 

Hope this helps :)

+8
source share

As Saddam shows, IsDefined more efficient than GetCustomAttributes . This is to be expected.

As described here , applying the MyAttribute attribute to the MyClass class is conceptually equivalent to instantiating the MyAttribute . However, instantiation does not actually occur unless MyClass is requested for attributes, as with GetCustomAttributes .

IsDefined , on the other hand, does not instantiate MyAttribute .

+1
source share

All Articles