NDepend

Improve your .NET code quality with NDepend

12 Visual Studio Debugging Productivity Tips

In this post we assume the the reader knows the basics of debugging with Visual Studio:

  • F5 to start running with the debugger
  • F9 set breakpoint on the current line
  • F10 run till next breakpoint
  • F5 to resume the execution from a stopped program debugged
  • F11 step into the function (if the instruction pointer points to a function)
  • F10 step over the function (if the instruction pointer points to a function)
  • Shift+F11 step out the executed function
  • Pause execution
  • Attach to Process
  • Quick watch an element in source code with mouse hover
  • Debug Windows : Locals, Watch, Immediate, Modules, Stack Trace, Exception

Many developers handle their debugging sessions with this powerful-enough knowledge kit. However the Visual Studio Debugging tools have much more to offer. Here is a list of Visual Studio Debugging productivity tips. Note that those tips and shortcuts have been validated with Visual studio 2019 16.6 EN-US edition with no extension installed.

1) Run to Cursor

With the shortcut Ctrl+F10 you can tell the debugger to run until the line pointed by the cursor.

Run to Cursor Ctrl+F10
Run to Cursor Ctrl+F10

2) Run through here with a mouse click

When hovering the source code while debugging a Run execution through here green glyph appears. This glyph can be clicked.

Run Execution Through Here Glyph
Run Execution Through Here with a Mouse Click

3) Set next statement to here

The Run execution through here green glyph can be transformed into Set next statement to here by holding the key Ctrl. It is different than Run execution through here because the statement in between are not executed. Hence in the small animation below we can see in the Watch window that the reference obj remains null: the MyClass constructor in between hasn’t been executed.

Set next statement to here
Set next statement to here

4) Data breakpoint: Break when value changes

If you set a breakpoint to a non-static property setter it will be hit when changing the property value for all objects. The same behavior can be obtained for a single object thanks to the Locals (or Watch) window right click : Break When Value Changes menu.

This facility is illustrated with the animation above. The hit occurs only when obj2.Prop is changed, not when obj1.Prop is changed.

Note that a data breakpoint is bound to a live object during a debugging session. Hence it gets lost once the debugged process stops, it cannot be reused during future debugging session.

Note that the menu Break When Value Changes is also available when right clicking a field in the Locals window but unfortunately the debugger doesn’t break on field change, I am not sure if it’s a bug or a feature not yet implemented?

Data breakpoint: break when value changes
Data breakpoint: break when value changes

5) Conditional breakpoint

A condition can be attached to a breakpoint to break only in a certain scenario. In the animation below we define the breakpoint with condition i > 6 within the loop. Then we click Continue and can see that once the breakpoint is stopped, the i value is actually 7.

Conditional Breakpoint
Conditional Breakpoint

6) Trace breakpoint

Halting the program execution is the most common action upon a breakpoint hit. However you can choose instead to print some traces in the Output window without (or with) halting. This possibility is illustrated by the animation below where we trace the value of i from 0 to 9 in the Output window. Notice that a trace breakpoint has the diamond shape in the code editor gutter.

Note that both a condition and a trace action can be specified on a breakpoint.

Trace Breakpoint
Trace Breakpoint

7) Track Objects that Are Out-Of-Scope

In the Watch window objects are tracked by the name of their references in the currently executed scope. However when such tracked reference goes out-of-scope, it becomes meaningless in the context of the Watch window and it gets disabled, even though the referenced object is still live.

There are many situations where we’d like to continue tracking the state of an out-of-scope object. To do so, right click such reference in the Watch window, click the menu Make Object ID and add $1 in the items to watch (or $2 or $3… depending on how many object IDs you’ve already created).

The animation belows shows how to track the state of an out-of-scope object’s property getter that returns the actual date-time as a string. It shows well that when the reference obj goes out-of-scope in the context of Fct(), obj item to watch gets disabled and $1.Prop still gets updated.

Tracking an object whose reference goes out-of-scope
Tracking an object whose reference goes out-of-scope

8) View values returned by functions

The value returned by a function is sometime ignored by the source code. Or sometime this value is just not obviously accessible at debug-time.

Such returned value can be shown in the Debug > Windows > Autos windows. The pseudovariables $ReturnValue can also be used in the Immediate and Watch Windows to view the last function call returned value.

Note that the menu Debug > Windows > Autos is available only when the Visual Studio debugger is attached to a process and the program is halted by the debugger.

View the value returned by a function
View the value returned by a function

9) Reattach To Process

Since Visual Studio 2017 the Reattach to process Shift+Alt+P facility is proposed and it’s very handy. Once you’ve been attaching the debugger to a process Visual Studio remembers it and proposes to re-attach the debugger to the same process. Same is in italic because there is an heuristic here about the process identity:

  • If the process you’ve been attached to is still alive Reattach to process re-attach to it.
  • Else Visual Studio attempts to find a single process with the same previous process name and re-attach the debugger to it.
  • If several processes are found with this name, the Attach to Process dialog is opened with only those processes with same name shown
  • If no process with this name can be found the Attach to Process dialog is shown
Reattach To Process
Reattach To Process

Reattach To Process also works with debug session involving multiple processes. In this situation Visual Studio attempts to find all processes it has been attached to with the same heuristics explained above.

10) No-Side-Effect evaluation in Immediate Window and in the Watch Window

Sometime when evaluating an expression in the Immediate or in the Watch window some state gets changed. This behavior is often indesirable, you don’t want to corrupt the state of your debugged program just because you needed to evaluate the value of an expression. This situation is known as an Heisenbug , the term is a pun on the name of Werner Heisenberg, the physicist who first asserted the observer effect of quantum mechanics, which states that the act of observing a system inevitably alters its state.

To avoid changing any state you can suffix your expression with , nse (No-Side-Effect). This possibility is illustrated by the animation below (watch the _State value changing or not in the Watch window):

No Side Effect expression evaluation
No Side Effect expression evaluation

Here is ,nse used in the Watch window. This sample is less trivial than the previous one because of the Refresh evaluation button in the SideEffectFct() watched item.

No Side Effect expression evaluation in the Watch Window
No Side Effect expression evaluation in the Watch Window

11) Show Threads in Source

Debugging a multithreaded application is notoriously complex. Hopefully the Show Threads in Source button can help a lot.  It introduces marker icons in the editor gutter to keep track of the locations on which other threads are halted. This marker can be used to show the thread ids and eventually switch to another thread. Notice that a different marker glyph is shown if at least two threads are halted on the same location.

Show Threads In Source
Show Threads In Source

More tips to debug multithreaded applications are available in this Microsoft documentation: Get started debugging multithreaded applications (C#, Visual Basic, C++)

Here is the source code of this small demo if you’d like to play with it:

12) Debug source code decompiled from IL code

Often we depend on some black-box components: assemblies for which we don’t have the source code.

However when debugging a complex behavior it is convenient to observe and even debug the logic nested in black-boxes referenced. This is why since version 16.5 Visual Studio 2019 can generate some source code from compiled assemblies. Such source code is then debuggable. This feature is based on the OSS project ILSpy.

The decompilation menu can be proposed in the assembly right-click menu in the Modules window (as shown in the animation below) and in the Source Not Found or No Symbols Loaded dialogs.

Decompiling IL code to source code cannot be perfect because some source information is lost at compilation time. Hence this feature has a few limitations explained at the end of this official documentation: Generate source code from .NET assemblies while debugging.

Decompile IL code to source code that can be debugged
Decompile IL code to source code that can be debugged

Conclusion

Visual Studio shines but it especially shines when it comes to debugging. Here I tried to select some tips that are both quite hidden but often useful, I hope they will help improve your productivity.

 

 

10 Visual Studio Ninja Code Editor Productivity Tips

Among the multiple daily development tasks (planning, testing, refactoring, bug fix…) code edition is arguably the most satisfying one. Code edition can be even more satisfying and productive by mastering the following Visual Studio productivity tips. In my opinion these tricks are not optionals: they should be part of all Visual Studio developer skills.

1) Move one or several lines up and down

The line that contains the editing caret can be moved up and down with Alt+Up and Alt+Down.

The same way several lines selected can be moved up and down.

Move lines up and down with Alt+Up and Alt+Down
Move lines up and down with Alt+Up and Alt+Down

2) Rectangular Selection

Rectangular selection is very useful to quickly edit a code portion. This can be achieved with Alt+Shift+Arrows shortcuts.

Rectangular Selection with Alt+Shift+Up/Down/Left/Right.
Rectangular Selection with Alt+Shift+Arrows.

3) Multi-Lines Edition

Once mastering rectangular selection, it can be used to edit multiple lines at once:

Multiple Lines Edition
Multiple Lines Edition

4) Multi-Carets Edition

Often we need to repeat the same edition at multiple locations. To do so multiple carets can be defined with Ctrl+Alt+Mouse Click:

Multiple Carets with Ctrl+Alt+Mouse Click:
Multiple Carets with Ctrl+Alt+Mouse Click:

5) Multi-Carets Edition on Same Matches

Multiple carets can be set to next locations of the selected word. To do so first select the word and then use Ctrl+Shift+; .

Multiple carets can be set to all locations of the selected word with Ctrl+Shift+$ .

Same Match Selection
Same Match Selection

6) Expand / Contract Selection

You can expand the selection with Shift+Alt+= and contract it with Shift+Alt+.

Expand Selection
Expand Selection

7) Make Selection Uppercase / lowercase

You can Uppercase the selection with Ctrl+Shift+U and lowercase it with Ctrl+U

Make Selection Uppercase / lowercase
Make Selection Uppercase / lowercase

8) Outlining

The most important keyboard shortcut when it comes to outlining is Ctrl+M Ctrl+M. This shortcut expands / collapses the code portion that contains the caret.

Not all developers enjoy outlining and if you are one of those, you can discard it with Ctrl+M Ctrl+P.

Expand / Collapse Outlining
Expand / Collapse Outlining

9) Vertical Scrollbar Map Mode

The map mode is one of the most useful Visual Studio code editor facility. It does really help finding your way in source file.

Vertical Scrollbar Map Mode 
Vertical Scrollbar Map Mode

It can be set from Visual Studio > Tools > Options > Text Editor > All Languages > Scroll Bars > Behavior.

The width of the map can be: Narrow Medium Wide

Set Vertical Scrollbar Map Mode 
Set Vertical Scrollbar Map Mode

10) Bookmarks

When developing we often have to come back and forth through multiple locations in several source files. Fortunately you can concretely define this locations-set with bookmarks. Here are bookmarks shortcuts:

  • Ctrl+K, Ctrl+K to toggle a bookmark at caret position
  • Ctrl+K Ctrl+N go to Next bookmark
  • Ctrl+K Ctrl+P go to Previous bookmark
  • Ctrl+K Ctrl+L clear all bookmarks

Note that Visual Studio remembers bookmarks when closing it and restarting it.

Toggle Bookmarks with Ctrl+K, Ctrl+K
Toggle Bookmarks with Ctrl+K, Ctrl+K

11) Bonus: Visual Studio 2019 Clipboard Ring Preview

Ctrl+C copy some data to the clipboard. Actually Visual Studio maintains a clipboard ring to store several data.

With Visual Studio 2019 Ctrl+Shift+V shows a preview of the various data in the clipboard ring. This is quite useful to navigate through the copy history.

Visual Studio 2019 Clipboard Ring Preview
Visual Studio 2019 Clipboard Ring Preview

Conclusion: Visual Studio > Edit > Advanced

The Visual Studio menu Edit > Advanced is both a good start and a good reminder for code editor keyboard shortcuts.

There are more sub-menu including Bookmarks, Outlining, Intellisense and Multiple Carets.

Visual Studio Edit Advanced
Visual Studio Edit Advanced

I like the ninja-coder analogy because these tips must be repeated again and again as kata to be mastered in your daily coding routine.

Kata is a Japanese word meaning literally “form” referring to a detailed choreographed pattern of martial arts movements made to be practised alone, and also within groups and in unison when training. It is practised in Japanese martial arts as a way to memorize and perfect the movements being executed

Why not take 8 minutes now with this background theme and practice?

Be curious: there are many more Visual Studio facilities that will help becoming a ninja coder, first one being code snippets.

10 Visual Studio Solution Explorer Productivity Tips

The Visual Studio Solution Explorer panel is like home for Visual Studio users. It presents all projects, source files and items thanks to a treeview layout.

This panel is quite sophisticated and it is likely that you don’t use all the power of this great tool. Here are some tips:

1) Automatically Track active Item in Solution Explorer

On a large Visual Studio solution with hundreds or thousands of source files, the Visual Studio Solution Explorer button Sync with Active Document is often clicked to find your way.

Visual Studio Solution Explorer Sync with Active Document

This sync can be done automatically. For that you just need to check: Visual Studio  >  top menus   >  Tools  >  Options…  >  Projects and Solutions  > General  >  Track Active Item in Solution Explorer.

Track Active Item in Solution Explorer
Track Active Item in Solution Explorer

2) Improve Visual Studio Startup Performance

Visual Studio startup is faster with these 3 settings:

  • Allow parallel project initialization checked
  • Reopen documents on solution load unchecked
  • Restore Solution Explorer project hierarchy state on solution load unchecked

This tip is especially useful to accelerate Visual Studio Startup when opening a large solution.

Improve Visual Studio Startup Performance
Improve Visual Studio Startup Performance

3) Search in Visual Studio Solution Explorer

The shortcut Ctrl+; set the focus in the Visual Studio Solution Explorer search textbox and you can start typing your search term(s). If the Solution Explorer panel is not visible this shortcut makes it visible. When displaying search results the treeview hierarchy is kept so you know the location of matched items.

The search setting Search within file contents is set by default but can be turned off to restreint the search on file name only.

Search in Visual Studio Solution Explorer
Search in Visual Studio Solution Explorer

The search setting Search within external items is set by default to match files in External Dependencies folders. Turning it off prevents searching within the C/C++ External Dependencies folder. This setting is not related to C#, VB.NET and F# projects.

Search within external items
Search within external items

4) Browse Types, Methods and Fields

In Visual Studio Solution Explorer a source file item can be expanded to browse type(s), methods and fields declared in the source file. Types, methods and fields items are shown in the same order of their declarations in the source file. These items can be double-clicked to open the source declaration and right-clicked to show the related menus.

Visual Studio Solution Explorer Types, Methods and Fields Items
Visual Studio Solution Explorer Types, Methods and Fields Items

5) Filter File Opened or Pending Changes

Two filters are proposed:

  • Open Files Filter: This filter is especially useful when a code review or a change spawn on many files.
  • Pending Changes Filter: Often a refactoring session spawn on several files and this filter lets keep track of file changed.

It is also possible to create your own filter as explained in this documentation: Extend the Solution Explorer filter

Open Files or Pending Changes Filters
Open Files or Pending Changes Filters

6) Quickly Set the Startup Project

Most developers I know setup the startup project this way: 1) find the project in the Solution Explorer 2) right click the project and find in the long list of menus the Set as Startup Project menu.

Here is a quicker way : select the Solution item, Alt+Enter shortcut to view the Solution Property Pages dialog, there you can quickly chose the startup project in a combo-box and even define multiple startup projects:

Quickly Set the Startup Project
Quickly Set the Startup Project

7) Preview Selected Items on Project

When the checkbox Preview Selected Items is checked, when selecting a source file it is automatically opened in the preview tab. This feature is widely used but what you might not know is that this feature also work to open project files XML content!

Preview Selected Item Works on Project Item
Preview Selected Item Works on Project Item

8) Scope to a Single Project

Often a development session only concerns a single project. You can restreint the Visual Studio Solution Explorer to only a single project with the project right-click menu Scope to This.

Scope to a Single Project
Scope to a Single Project

9) Multiple Solution Explorer Views

I wish that the Scope to This facility shown above would be available when right-clicking several projects to restreint the focus on a few projects, but it is not.

However it is possible to work with multiple solution explorer views, each one scoping to a project. To do so right-click a project and click the menu New Solution Explorer View. Notice that extra Solution Explorer View(s) are not persisted. When you close and re-open Visual Studio they are not here anymore.

New Solution View
New Solution View

10) Switch to Folder Views

Most of the time the Visual Studio Solution Explorer displays assets structured in a logical way. For example solution folders used to group projects don’t necessarily represent real OS file system folders. It is often useful to switch to a physical presentation of the solution folders and files. This can be achieved with the Switch Views combo box.

Solution Explorer Folder View
Solution Explorer Folder View

11) Bonus: Explore Solution Architecture

The new NDepend powerful dependency graph is like a second Solution Explorer that focuses on the solution architecture. Folders and files can be drag-and-dropped from the Visual Studio Solution Explorer to the graph.

Drag and Drop from the Visual Studio Solution Explorer to the NDepend Dependency Graph
Drag and Drop from the Visual Studio Solution Explorer to the NDepend Dependency Graph

There are many more facilities presented in the videos below:

  • It can handle live very large solutions made of dozens or hundreds of projects.
  • Right clicking a solution explorer item like a project or a source file shows a menu to generate a graph of the item’s child, callers and callees.
  • Box size in the graph is proportional to the number of lines of code to get an intuitive view.
  • Items in the graph can be searched, expanded and collapsed the same way as in the Visual Studio Solution Explorer.
  • The graph has a navigation bar to quickly generate call graph, coupling graph, class diagram, graph of dependency cycles, graph of changes since baseline and more.