I don't think it's possible to do exactly what you want to do, since foreach
, to my knowledge, always calls the GetEnumerator()
without any arguments. However, I see two possibilities to your issue
You can use a StackTrace
to get the calling method:
public IEnumerator<string> GetEnumerator()
{
StackTrace stackTrace = new StackTrace();
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
return items.GetEnumerator();
}
or you can use another method instead of the GetEnumerator()
which takes the [CallerMemberName]
attribute.
public IEnumerable<string> Iterate([CallerMemberName]string caller = null)
{
Console.WriteLine(caller);
return items;
}
foreach (var myItem in items.Iterate())
{
//..
}