Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemberInfo.GetCustomAttributes extensions overload

Tags:

c#

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?

like image 226
nicecatch Avatar asked Apr 07 '26 15:04

nicecatch


2 Answers

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.

like image 168
Hans Passant Avatar answered Apr 09 '26 04:04

Hans Passant


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.

like image 41
poke Avatar answered Apr 09 '26 05:04

poke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!