nicecatch
nicecatch

Reputation: 1737

MemberInfo.GetCustomAttributes extensions overload

I noticed there are two methods (one class method and one extension method) with the same signature but different return types in package System.Reflection for class MemberInfo:

Class method:

public abstract object[] GetCustomAttributes(Type attributeType, bool inherit)

Extension method (inside CustomAttributeExtensions):

public static IEnumerable<Attribute> GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit)

I know that calling that method with such parameters will always invoke class method, so I am just wondering:

how to call extension method?

and, above all, what's the purpose of defining an extension with same signature as class method?

Upvotes: 3

Views: 2843

Answers (2)

Hans Passant
Hans Passant

Reputation: 942109

Having this kind of duplication in a framework is not exactly a feature. But this was a rock and a hard place, they had to add the extension method in .NET 4.5. Most readily visible from the bottom of the MSDN articles in the Version Information block. The extension method is usable in UWP and Phone projects, the legacy method is not.

Underlying reason is the language projection built into the CLR at 4.5. It makes the rather big difference between WinRT and CLR types highly invisible. WinRT would be still-born, more than it already was, if programmers had any inkling that it is actually COM under the hood that powers UWP :) Very well hidden, but the Type class was too heavily married to the CLR, they had to provide the TypeInfo class as an alternative. And extension methods to bridge the api gap.

If you don't target UWP then you don't have much use for the extension method and should favor the legacy method. The extension method is about 30% slower.

Upvotes: 6

poke
poke

Reputation: 388153

You are right, there is MemberInfo.GetCustomAttributes and CustomAttributeExtensions.GetCustomAttributes with effectively the same set of parameters.

If you look at the reference source for each, you can see that the extension method actually delegates back to Attribute.GetCustomAttribute. And that method will eventually get back to MemberInfo.GetCustomAttributes.

So is there a functional difference between those two? No, not really. Then what is the reason why this extension method exists? I unfortunately have no clue. The major benefit of CustomAttributeExtensions are the generic overloads anyway which allow you to get typed attributes back, so I don’t think you would actually want to use GetCustomAttributes in a usual situation.

Upvotes: 2

Related Questions