views:

259

answers:

2

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);
+2  A: 

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).

Noldorin
+1  A: 

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
            ("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?

Jon Skeet