this. __curious_geek
this. __curious_geek

Reputation: 43207

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.

Upvotes: 5

Views: 2977

Answers (1)

Sam Saffron
Sam Saffron

Reputation: 131112

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();
    }
}

Upvotes: 12

Related Questions