Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 594
Selman Genç Avatar asked May 23 '14 13:05

Selman Genç


People also ask

What is the purpose of the modifier out applied to a parameter in a method definition?

The out keyword causes arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument.

What is a method parameter modifier?

They are few keywords that are use to control how arguments are passed to the method. (None): If parameter is not marked with a parameter modifier,it is assumed to be passed by value, meaning the called method receives a copy of the original data.

How do you call a method which has parameters?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.

What is the difference between ref & out parameters?

ref is used to state that the parameter passed may be modified by the method. in is used to state that the parameter passed cannot be modified by the method. out is used to state that the parameter passed must be modified by the method.


1 Answers

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.

like image 195
Jon Skeet Avatar answered Nov 15 '22 08:11

Jon Skeet