Naming is Hard

Icon

Written by Bruce Boughton

Debugging IEnumerable.GetEnumerator

I’ve been working a lot recently with IEnumarable objects as generators. I think it’s a really nice pattern, which allows you to defer processing until it is needed. For example,

foreach (LogEntry entry in logreader)
    /* Do something with the log entry */

(LogReader does not need to read all lines in advance; instead it can read each line as it is requested)

One irritant I’ve encountered with GetEnumerator is that it can be quite hard to debug if you access class fields. The compiler transforms the GetEnumerator method body into a nested class. In the Locals window in visual studio you can’t access your class’s fields and when hovering over variables you don’t get pop-up introspection.

It is possible, however, to access your class’s fields and properties via reflection. The generated GetEnumerator class stores a reference to your class in a private field which is not exposed to the Locals window. In my experience, this is the only field in the generated class so you can access its value using the Immediate window like so:

this.GetType().GetFields()[0].GetValue(this)

If this isn’t what you’re expecting, look at the array of fields returned and find the one that holds the reference to your class (usually named something like <>4__this).

Update: If you want to access the member fields, properties and methods of your class you need to cast it to your type. To avoid doing this repetitively, you can create a variable holding the cast reference in the Immediate window:

Foo me = (Foo)this.GetType().GetFields()[0].GetValue(this);
me.Bar;
me.SomeMethod();

Category: .NET

Tagged:

Comments are closed.