How to call extension method using reflection ?
I tried this code but methodInfo is null.
Andrus.
using System.Reflection;
using System.Windows.Forms;
public class Customer { }
public static class CustomerExtension {
public static string FindById(this Customer c, string id) {
return "";
}
}
class Program {
static void Main() {
MethodInfo methodInfo = typeof(Customer).GetMethod("FindById",
BindingFlags.Public | BindingFlags.FlattenHierarchy
| BindingFlags.Static);
MessageBox.Show((methodInfo == null).ToString());
}
}
Jon Skeet [C# MVP] - 05 Jan 2008 22:38 GMT
> How to call extension method using reflection ?
Find the static method and call it like any other static method.
Extension methods are entirely a compile-time deal.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Marc Gravell - 05 Jan 2008 23:35 GMT
Further to Jon's answer - it is *broadly* possible to check for
matching public static methods over all assemblies, checking for
ExtensionAttribute (I have a sample that illustrates this), but this
is *not* robust (i.e. don't use it; ever): it is entirely possible to
have multiple extension methods (named the same) that could satisfy an
extension invoke, but which one gets called depends entirely on which
"using" statements are included in the source cs. Hence to do this
*properly* you'd need to inspect the IL of the method body.
Additionally, a complication is that you'd need to consider all
"assignable from" variants of the various arguments, making searching
tricky.
At compile time, the compiler simply substitutes direct calls to the
static method, as if you had written:
CustomerExtension.FindById(cust,id);
instead of:
cust.FindById(id);
Hence you'd be best looking at CustomerExtension if you know about
this class in your code.
Marc