Is there a way to determine whether a parameter has this modifier?

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow