Search code examples
c#reflectionanonymous-methods

How to identify anonymous methods in System.Reflection


How can you identify anonymous methods via reflection?


Solution

  • Look at the attributes of the method, and see if the method is decorated with CompilerGeneratedAttribute.

    Anonymous methods (as well as other objects, such as auto-implemented properties, etc) will have this attribute added.


    For example, suppose you have a type for your class. The anonymous methods will be in:

    Type myClassType = typeof(MyClass);
    IEnumerable<MethodInfo> anonymousMethods = myClassType
        .GetMethods(
              BindingFlags.NonPublic
            | BindingFlags.Public 
            | BindingFlags.Instance 
            | BindingFlags.Static)
        .Where(method => 
              method.GetCustomAttributes(typeof(CompilerGeneratedAttribute)).Any());
    

    This should return any anonymous methods defined on MyClass.