Welcome to MSDN Blogs Sign in | Join | Help

Marcelo's WebLog

Improving the world one entity at a time
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!

Posted: Tuesday, March 31, 2009 2:00 PM by marcelolr
Filed under:

Comments

realparadyne said:

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 :-)

# April 1, 2009 5:59 AM

marcelolr said:

Good point... Should have tagged this as performance as well :)

# April 1, 2009 3:44 PM
New Comments to this post are disabled
Page view tracker