5

I would like to determine if a parameter has this modifier using Reflection.I have looked at properties of ParameterInfo class, but couldn't find anything useful.I know the extension methods are just syntactic sugars but I believe there should be a way to determine whether a method is an extension method.

The only thing that distinguishes extension methods from other static methods (that are defined in a static, public class) is this modifier.

For example this is not an extension method:

public static int Square(int x) { return x * x; }

But this is:

public static int Square(this int x) { return x * x; }

So how can I distinguish between two methods using Reflection or something else if possible?

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • 2
    Possible duplicate of [Using reflection to check if a method is “Extension Method”](http://stackoverflow.com/questions/721800/using-reflection-to-check-if-a-method-is-extension-method)? – Red Taz May 23 '14 at 13:28
  • In each language that supports them, there are two sides to extension methods: invoking (reflection at compile-time) and declaring (source code). See the relevant spec. [[C# 5.0](http://msdn.microsoft.com/en-us/library/ms228593.aspx) section 7.6.5.2 Extension method invocations, section 10.6.9 Extension methods.) – Tom Blodget May 23 '14 at 15:41

1 Answers1

8

It's not exactly the same, but you can check whether the method has the ExtensionAttribute applied to it.

var method = type.GetMethod("Square");
if (method.IsDefined(typeof(ExtensionAttribute), false))
{
    // Yup, it's an extension method
}

Now I say it's not exactly the same, because you could have written:

[Extension]
public static int Square(int x) { return x * x; }

... and the compiler would still pick it up as an extension method. So this does detect whether it's an extension method (assuming it's in a static top-level non-generic type) but it doesn't detect for certain whether the source code had the this modifier on the first parameter.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194