Compartir a través de


GetCurrentMethod and lambdas - watch out

Got bit by this a few moments ago... Thankfully it didn't take long, but probably because this was fairly isolated in my case; I could imagine getting stuck for a bit longer if this were a larger piece of code.

Anyway, I was running method that goes through a array and looks for a reference to the method itself, using MethodBase.GetCurrentMethod. I had the following code.

public void AnInterestingMethod()
{
  var result = Thingy.ListInterestingMethods(this.GetType().Assembly);
  Assert.IsTrue(result.Any(method => method == MethodBase.GetCurrentMethod()));
  ...

And yet I wasn't finding a match. After looking at this for a bit, I realized that of course the GetCurrentMethod call won't execute in this method, but in the lambda, with its own anonymous function.

The following rewrite shows finds the method as expected.

public void AnInterestingMethod()
{
var result = Thingy.ListInterestingMethods(this.GetType().Assembly);
MethodBase m = MethodBase.GetCurrentMethod();
Assert.IsTrue(result.Any(method => method == m));
...

Now the GetCurrentMethod call executes in the interesting method itself, which of course makes it show up in the list.

Enjoy!

Comments

  • Anonymous
    March 31, 2009
    And of course the second version only calls GetCurrentMethod() once instead of once for each item in the list, so it's more efficient too :-)

  • Anonymous
    April 01, 2009
    Good point... Should have tagged this as performance as well :)