Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke Generic Extension method on an Object?

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.

like image 288
this. __curious_geek Avatar asked Jun 26 '09 06:06

this. __curious_geek


1 Answers

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();
    }
}
like image 88
Sam Saffron Avatar answered Oct 10 '22 03:10

Sam Saffron