Calling extension method using reflection



How to call extension method using reflection ?

I tried this code but methodInfo is null.


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]

Andrus said:
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.



Marc Gravell

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

At compile time, the compiler simply substitutes direct calls to the
static method, as if you had written:
instead of:
Hence you'd be best looking at CustomerExtension if you know about
this class in your code.


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question