How to identify anonymous methods in System.Reflection
Asked Answered
K

3

8

How can you identify anonymous methods via reflection?

Khufu answered 23/3, 2010 at 20:25 Comment(1)
Could you say some more about what you want to accomplish?Iveson
W
10

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.

Wrongdoer answered 23/3, 2010 at 20:27 Comment(7)
And so can any other method (or member/type).Bobine
True - you can define this manually on any method, and fool it, but typically, this is used for anonymous methods and other compiler generated information.Wrongdoer
For auto properties too, and on property getters and setters.Bobine
Granted, this is not a fail-safe way to do this, as there is no such thing as "anonymous", but "anonymous" typically means a compiler-generated type.Wrongdoer
@Leppie: I just changed the language - that help?Wrongdoer
leppie - auto property getter/setter methods have the IsAccessor == true.Khufu
This does not work on UWP for some reason. The attribute is not there.Bestead
S
9

You cannot, because there is no such thing as an anonymous method on IL level - they're all named, and all belong to named types. And the way C# and VB compilers translate anonymous methods to named methods and types is entirely implementation-defined, and cannot be relied on (which means that, for example, it can change with any update, even in minor releases / hotfixes).

Statolatry answered 23/3, 2010 at 20:38 Comment(1)
+1: This is, technically, the "correct" answer - but [CompilerGenerated] works fairly reliably in practice.Wrongdoer
B
5

From what I can see, that Regex pattern would be:

<(\w|_)+>b_.+
Bobine answered 23/3, 2010 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.