Reputation: 7136
I am working with a lot of lambda expressions of type Action<>
and Func<>
that are being passed down parameters and I finding it hard to keep track of what the actual code those variables represent. It is possible to see during debugging in Locals
windows or Watch
windows actual code of those lambdas ?
ex. Action<Exception, int> doNothing = (_, __) => { };
when doNothing
is passed down a method as parameter, I would like to see (_, __) => { }
somewhere in the Locals
or Watch
windows.
Upvotes: 2
Views: 239
Reputation: 271820
You can't directly see the contents of a delegate. They are designed to not know anything about what they themselves will do upon calling Invoke
.
Action a = () => Console.WriteLine(); // getting "Console.WriteLine()" from "a" is not possible.
But the debugger can help you figure out what the lambda is.
You can write expressions in the "Immediate" window to evaluate them.
Func<int, int> negate = x => -x; // let's say you can't see this line but you know "negate" exists.
// in Immediate window, you can write the following
// negate.Invoke(1) // -1
// negate.Invoke(-1) // 1
// then you can guess that "negate" will negate the number, though not conclusively
However, I think the best way is to trace back your code to see where that delegate came from. This way, you can find the original method/lambda that was added to the delegate.
You mentioned that the delegate is passed to a method as a parameter. This means that you can look down the stack trace and see which method called that method. The delegate might be created there. If not, look down the stack again until you can find it.
If the delegate is stored in a field/property, then you have to search for when that field/property is set, which can be hard.
EDIT:
See this post: What are C# lambda's compiled into? A stackframe, an instance of an anonymous type, or?
Lambdas are compiled into, essentially, methods of some type. Can you "see" the implementation of a method in the debugger? No.
Upvotes: 1