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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With