1

So in JavaScript, you can call toString() on a function to return it's source code. However, no such construct exists for C# delegates.

Let's say I have this code sample here:

void DoThing()
{
    Console.WriteLine("I did a thing");
}

void Execute(Action act)
{
    act();
}

public static int Main(string[] args)
{
    Execute(DoThing);
    Execute(() => Console.WriteLine("llama lambda"));
}

If I debug this code in Visual Studio 2019, and put a breakpoint on Execute, I can look at the properties of act.

For the first call with DoThing, Visual Studio can at least give me the name of the method and it's return type (Void DoThing()), but not the source code. If I have multiple DoThings in my source code, this will not be very helpful at all.

But for the lambda, I get no useful info in the debugger ({Method = {Void <Process>b__11_0()}}).

Now, of course in this small example code, it is pretty easy to find the functions by just retracing the call stack, but in some cases, this is a very long and arduous endeavour, especially when it needs to be done multiple times.

I searched around on google and I couldn't find a simple answer to this question, or even find anywhere where this question was asked:

Is there any way to find the source code of a delegate in C# when using the Visual Studio debugger (without just retracing the call stack)?

If yes, how?

And if no, why?

NotAPro
  • 136
  • 2
  • 17
  • 1
    Visual studio is displaying something like `act.Method.Name`, you could watch `act.Method.DeclaringType.Name`, but lamda's are compiled into a generated type (eg https://sharplab.io/#v2:EYLgtghglgdgNAExAagD4AEBMBGAsAKHQGYACLEgYRIG8CT6yAWEgUQA8BTAYwFcAXDgAp02TCQhc+ASjoNa+BovGTBUgNyz6AXwKaypdMwCyqmnsXtu/IaYC8APjLYAnIIBEAGw8RIJb2GAECDcpdT0dfC0gA==) – Jeremy Lakeman Oct 21 '21 at 00:47
  • @JeremyLakeman This information is useful, but it doesn't necessarily explain _why_ I can't see the source code of the function. Even if the lambda gets compiled like that, it still **runs code,** which I could potentially see. If the compiler knows what code to run, surely it could show it to me, right? – NotAPro Oct 24 '21 at 22:26
  • There probably is a way to use `MemberInfo.MetadataToken` to locate debug information and then the relevant source code. Visual Studio *could* use that, but doesn't. Since you can use the debugger to step into a method, is this missing feature going to be valuable to developers? (https://learn.microsoft.com/en-us/visualstudio/ide/suggest-a-feature?view=vs-2019) – Jeremy Lakeman Oct 25 '21 at 00:06

0 Answers0