As you can probably guess, the problem is that the yield return
does a bit of rewriting behind the scenes, much like a using
statement or lambda does. It is actually implemented as an enumerator with code that calls yield return
, which is part of the MoveNext
method in the enumerator.
This is a common problem with using Reflection: it gives you information about the runtime of your executable code, which may not coincide with your idea of โโcompiling what kind of code it is.
This is a long way to say that there is no easy way to get the information you need. If you would move the yield return
further into a separate method, then any code outside this method would not be part of MoveNext
, but this may or may not do what you need. You no longer get the name of the method that performs yield return
, you get the name of its caller. If thatโs all you care about, it looks like this:
public IEnumerable<string> Something { get { var x = MethodBase.GetCurrentMethod().Name; return this.DoSomething(x); } } private IEnumerable<string> DoSomething(string x) { for (int i = 0; i < 5; i++) { yield return x; } }
EDIT: although I doubt this will help you in the short term, for writing this problem has also been resolved using the new C # 5 attributes. Since the CallerMemberName
attribute CallerMemberName
resolved at compile time and, apparently, before the iterator was rewritten into an enumerator class, it returns the property name:
public IEnumerable<string> Something { get { var x = this.GetCallerName(); for (int i = 0; i < 5; i++) { yield return x; } } } private string GetCallerName([CallerMemberName] string caller = null) { return caller; }
source share