views:

226

answers:

1

Let's say that I have the following delegate:

public delegate void Example();

and a class such as the following:

public class TestClass {
    Example FailingTest = () => Assert.Equal(0,1);
}

How can I use reflection to get the name "FailingTest"?

So far I have tried:

var possibleFields = typeof(TestClass).GetFields(relevant_binding_flags)
                            .Where(x => x.FieldType.Equals(typeof(Example)));

foreach(FieldInfo oneField in possibleFields) {
  // HERE I am able to access the declaring type name
  var className = oneField.ReflectedType.Name; // == "TestClass"

  // but I am not able to access the field 
  // name "FailingTest" because:
  var fieldName = oneField.Name; // == "CS$<>9__CachedAnonymousMethodDelegate1"
}

Stepping through in the debugger, I am unable to find a path to the name of the declared field, "FailingTest".

Is that info retained at runtime or is it lost when the anonymous delegate is assigned?

+3  A: 

What BindingFlags are you passing to GetFields? I used these:

BindingFlags.NonPublic | BindingFlags.Instance

and I was able to see the name of the field.

Andrew Hare
I got the same results, using VS2008SP1.
Andy
That worked for me; somehow I missed BindingFlags.Instance and was trying to get this info from the Type then read the anonymous method value from ; using an instance did the trick. Thanks!
David Alpert