views:

440

answers:

1

Hi,

I have created a Generic Extension method for DataRow object. The method takes no argument. I want to Invoke the Generic method through Reflection using MethodInfo. I can do this for Normarl public methods, but somehow I cannot get the reference of the Generic Extension method.

I've read this question on SO which somehwat relates to my query, but no luck that way.

+2  A: 

Keep in mind that extension methods are compiler tricks. If you look up the static method on the static class where the extension method is defined you can invoke it just fine.

Now, if all you have is an object and you are trying to find a particular extension method you could find the extension method in question by searching all your static classes in the app domain for methods that have the System.Runtime.CompilerServices.ExtensionAttribute and the particular method name and param sequence in question.

That approach will fail if two extension classes define an extension method with the same name and signature. It will also fail if the assembly is not loaded in the app domain.

The simple approach is this (assuming you are looking for a generic method):

static class Extensions {
    public static T Echo<T>(this T obj) {
        return obj;
    }
}

class Program {

    static void Main(string[] args) {

        Console.WriteLine("hello".Echo());

        var mi = typeof(Extensions).GetMethod("Echo");
        var generic = mi.MakeGenericMethod(typeof(string));
        Console.WriteLine(generic.Invoke(null, new object[] { "hello" }));

        Console.ReadKey();
    }
}
Sam Saffron
Does it mean that I need to fetch the MethoInfo reference from the class which defines the ExtensionMethod and then Invoke it on the Object which hosts the ExtensionMethod at runtime ???
this. __curious_geek
its a static method, so you do not invoke it on an object, the object is the first param to the method.
Sam Saffron
So it means, It will throw an Exception when I try to fetch the reference.
this. __curious_geek
See working sample
Sam Saffron