Jay Walker Jay Walker - 2 years ago 96
C# Question

Is there a benefit of using IsDefined over GetCustomAttributes

Consider the case where an assembly contains one or more types attributed with a custom attribute

and you need to get a list of these types. Is there any benefit of using IsDefined vs. GetCustomAttributes aside from the more compact syntax? Does one expose/hide something that the other doesn't? Is one more efficient than the other?

Here is a code sample demonstrating each usage:

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;

Answer Source

Done a quick test with the two methods and it seems IsDefined is a lot faster than GetCustomAttributes

200000 iterations

IsDefined average Ticks = 54
GetCustomAttributes average Ticks = 114

Hope this helps :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download