How can you identify anonymous methods via reflection?
Asked
Active
Viewed 1,816 times
7
-
Could you say some more about what you want to accomplish? – Mikael Svenson Mar 23 '10 at 20:28
3 Answers
9
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
.

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
-
-
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. – Reed Copsey Mar 23 '10 at 20:37
-
1
-
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. – Reed Copsey Mar 23 '10 at 20:39
-
-
leppie - auto property getter/setter methods have the IsAccessor == true. – devlife Mar 23 '10 at 23:59
-
This does not work on UWP for some reason. The attribute is not there. – Shahar Prish Feb 13 '18 at 08:52
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).

Pavel Minaev
- 99,783
- 25
- 219
- 289
-
3+1: This is, technically, the "correct" answer - but [CompilerGenerated] works fairly reliably in practice. – Reed Copsey Mar 23 '10 at 20:44