As far as I know, the C# extension method has the attribute of 'System.Runtime.CompilerServices.ExtensionAttribute'
so i wrote simple test and I check with ilspy and this does not exist there.
I also on creating an object instance and investigating the instance method - I can't recognize if some method is an extension method or not.
I also look on the il viewer but on the viewer i see the 'System.Runtime.CompilerServices.ExtensionAttribute'
I looking for another way to know if some object/assembly method are extension method from runtime code.
(.net core 6.0)
CodePudding user response:
Pretty easily, just check whether a given MethodInfo
has the ExtensionAttribute
applied to it using the GetCustomAttributes(Type, bool)
method
So:
public static bool IsExtensionMethod(this MethodInfo method)
{
// The 'false' is because static classes must derive from 'object'
// So checking for inherited attributes is unnecessary
return method.GetCustomAttributes(typeof(ExtensionAttribute), false).Length > 0;
}
FWIW I recommend not looking at IL directly (unless you really need to), instead I recommend you use something like Sharplab to decompile the C# code to actually see what gets compiled, as "code lowering" (sometimes also called desugaring/ stripping syntactic sugar away) is one of the first steps the compiler does