0

Code I have:

public enum ActivityStatus
{
    All = 0,
    Active = 1,
    Inactive = 2
}

public static class MyClass
{
    public static string Test(this ActivityStatus _value) { return _value + "111"; } 
}

And typeof(ActivityStatus).GetMethods() doesn't contain Test method. I even tried to put everything in the same assembly, but still no success. Where I am wrong?

Vladimirs
  • 8,232
  • 4
  • 43
  • 79

2 Answers2

1

Why do you expect it to be there? The enum has no methods. The extension method is in class MyClass. The fact that you can call it with a different syntax so it looks just like a method of ActivityStatus is just syntactic sugar on top.

typeof(MyClass).GetMethods()

should return the method if you use the proper binding flags (public, static) .

nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

Extension methods are just static methods, compiler translates this call

yourEnum.Test();

to:

MyClass.Test(yourEnum);

So in order to get Test method info via reflection, you need to inspect MyClass, ActivityStatus is just a parameter there.

var testMethodInfo = typeof(MyClass).GetMethod("Test");
var firstParameter = testMethodInfo.GetParameters()[0];

Console.WriteLine (firstParameter.ParameterType + " " + firstParameter.Name);

prints:

ActivityStatus _value

If you want to get all extension methods for type in a particular assembly, you can use next code:

var extensionMethodsForActivityStatus = 
        typeof(ActivityStatus) //type from assembly to search
           .Assembly  //pick an assembly
           .GetTypes() //get all types there 
           .SelectMany(t => t.GetMethods()) //get all methods for that type
           .Where(m => m.GetParameters().Any() &&
                       m.GetParameters().First().ParameterType == typeof(ActivityStatus)) //check if first parameter is our enum
           .Where(m => m.IsDefined(typeof(ExtensionAttribute), true)); //check if the method is an extension method

foreach(var extensionMethod in extensionMethodsForActivityStatus)
    Console.WriteLine(extensionMethod.Name); //prints only Test
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90