Easily navigate code delegates while debugging

Mark Downie

Delegates are everywhere in modern code; a delegate is a type that represents references to methods with a particular parameter list and return type. Developers use delegates to pass methods as arguments to other methods. One example you may be familiar with is with event handlers. Handlers are methods you can invoke through delegates. Delegates remind me of C++ function pointers, but of course delegates are fully object-oriented.

There are a few ways to represent delegates, there is, for example, Func delegate. This generic delegate represents a method that takes one or more parameters and returns a value of a specified type. Here is an example (with a lambda expression):

Func<int, int> Multiplier = n => n * 5;
int val = Multiplier(5);
Console.WriteLine(val);

The most recent variation of this concept is Action, which provides a more convenient shorthand. When you use Action you do not have to explicitly define a delegate that encapsulates a method with a single parameter. Here is an example:

Action<string> outputFunc = GetOutputRoutine();
outputFunc("Hello, World!");

static Action<string> GetOutputRoutine()
{
   return MyConsoleWriter;
}

static void MyConsoleWriter(string input)
{
   Console.WriteLine("Console: {0}", input);
}

So, this is a nice lesson, but why am I mentioning all this? While I find passing methods around like parameters is convenient when writing code, I also wish it were easier to follow while debugging. You can of course easily step into these methods, but I often want to quickly navigate to the underlying code represented by the delegate before or after stepping, and with the latest updates to Visual Studio 17.10 it’s incredibly easy.

When you pause while debugging, you can hover over any delegate and get a convenient go to source link, here is an example with a Func delegate.

Visual Studio debugging func goto source

The Go to Source indicator makes it clear, in this example, that you will get redirected back to the lambda expression.

Please note this is not just for managed code situations, this also supports C++ function pointers and std::function.

We appreciate your feedback to help us improve Visual Studio and make it the best tool for you! You can share feedback with us via Developer Community: report any bugs or issues via report a problem and share your suggestions for new features or improvements to existing ones.

Please stay connected with the Visual Studio Debugger team on Twitter.

 

Feedback usabilla icon