Using reflection to check if a method is "Extension Method"
Asked Answered
B

5

18

As part of my application I have a function that receives a MethodInfo and need to do specific operations on it depending if that method is "Extension Method".

I've checked the MethodInfo class and I could not find any IsExtension property or flag that shows that the method is extension.

Does anyone knows how can I find that from the method's MethodInfo?

Bevan answered 6/4, 2009 at 14:47 Comment(1)
related: reflection-to-identify-extension-methodsJusticiar
U
19

Based on

F# extension methods in C#

it seems there is an attribute on the compiled form. So see if the method has this attribute:

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx

Ursula answered 6/4, 2009 at 14:51 Comment(0)
S
25

You can call the IsDefined method on the MethodInfo instance to find this out by checking to see if the ExtensionAttribute is applied to the method:

bool isExtension=someMethod.IsDefined(typeof(ExtensionAttribute),true);
Sergio answered 6/4, 2009 at 14:57 Comment(0)
U
19

Based on

F# extension methods in C#

it seems there is an attribute on the compiled form. So see if the method has this attribute:

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx

Ursula answered 6/4, 2009 at 14:51 Comment(0)
G
3

This looks very similar to an earlier question, might be worth a look. The suggestion there was to look for classes and methods with the ExtensionAttribute which sounds like what you are after.

Grainger answered 6/4, 2009 at 14:53 Comment(0)
C
1

If you know you are getting a MethodInfo from an instance, you can easily check if the method is static. Extension methods are just syntactic sugar and get transformed into static method calls passing in the instance.

Covalence answered 6/4, 2009 at 14:50 Comment(0)
S
0

Doesn't the compiler switch all extension methods into static method calls at compile time?

myList.First();

becomes

Enumerable.First(myList);

If this is the case, then there are no extension methods in the .net runtime (where you are reflecting).

Synchroscope answered 6/4, 2009 at 14:51 Comment(1)
That last sentence is wrong, there are extension methods. You just cannot tell him apart from static methods.Covalence

© 2022 - 2024 — McMap. All rights reserved.