Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MethodInfo for Extension Method

I cant get the method info for an extension method as I would suspect. Whats wrong?

_toStringMethod = typeof(ObjectExtensions).GetMethod("TryToString",
    BindingFlags.Public | BindingFlags.Static);
like image 421
chief7 Avatar asked Jun 12 '09 16:06

chief7


2 Answers

Works for me:

using System;
using System.Reflection;

public static class ObjectExtensions
{
    public static string TryToString(this object x)
    {
        // Just guessing...
        return x == null ? "" : x.ToString();
    }
}

class Test
{
    static void Main()
    {
        var method = typeof(ObjectExtensions).GetMethod(
            nameof(ObjectExtensions.TryToString),
            BindingFlags.Public | BindingFlags.Static);
        // Prints System.String TryToString(System.Object)
        Console.WriteLine(method);
    }
}

Can you give a similar short but complete example which fails?

like image 104
Jon Skeet Avatar answered Oct 23 '22 02:10

Jon Skeet


Works for me. Just check that your method class, name, and modifier are all correct.

As a note, there is no reason that it shouldn't work under any circumstances. Extension methods are still "normal" methods in that they belong to the static class in which the defined. It is only the way you access them that differs (though you can still access them normally too, of course).

like image 20
Noldorin Avatar answered Oct 23 '22 02:10

Noldorin