locked
Extension methods and reflection

    Question

  • Hi!

    Is it possible to invoke an extension method at runtime using reflection?
    According to Rezaei's blog, I can't use GetMethod to discover extension methods. So, how could I invoke an extension method by its name?

    Thanks
    Saturday, July 28, 2007 6:10 PM

Answers

  •  

     

    From my understanding, you can, but you need to know the class that is actually defining the method, not the class it's applied to.  Remember, extension methods are just a compiler "trick".  When you look at the code


    List<int> someList = new List<int>();

    someList.Extension(1);

    it seems like Extension() is defined on the class List`1. But it could actually be nearly anywhere (lets say on a class named ExtenderClass in a third party assembly we're referencing).   Once the code is compiled, all trace of it being an extension method is gone.  If you "de-compiled" the il to c#, that same call would look like  :

     

    List<int> someList = new List<int>();

    ExtenderClass.Extension( someList, 1);

    So, to call via reflection, you need to reflect on ExtenderClass,  not on List`1.

    Saturday, July 28, 2007 11:33 PM

All replies

  •  

     

    From my understanding, you can, but you need to know the class that is actually defining the method, not the class it's applied to.  Remember, extension methods are just a compiler "trick".  When you look at the code


    List<int> someList = new List<int>();

    someList.Extension(1);

    it seems like Extension() is defined on the class List`1. But it could actually be nearly anywhere (lets say on a class named ExtenderClass in a third party assembly we're referencing).   Once the code is compiled, all trace of it being an extension method is gone.  If you "de-compiled" the il to c#, that same call would look like  :

     

    List<int> someList = new List<int>();

    ExtenderClass.Extension( someList, 1);

    So, to call via reflection, you need to reflect on ExtenderClass,  not on List`1.

    Saturday, July 28, 2007 11:33 PM
  • Thanks, I already tried to search static "original" methods and it works.
    I was searching for alternative ways with no needs to specify the extender class, but if the compiler itself translates it in a static call, then this is the only way possible.

    Thanks for reply
    Sunday, July 29, 2007 4:30 AM