Visual Studio 2017 – Exception Helper

Exceptions is an ancient programming concept that every developer has to deal with in the programs they write during development, testing and production scenarios. Visual Studio has long provided facilities to inspect the exceptions but with Visual Studio 2017, its Exception Helper dialog makes that process even easier.

In order to set the stage, let’s look at the following piece of code, specially the line shown in red rectangle below.

1

As you can see, there are various properties invoked for different objects on this line without ensuring that these objects are not null. This type of code can cause tricky situations to deal with specially in a production environment as I described in one of my article for Visual Studio Magazine.

Let’s say, when debugging this application in Visual Studio 2015, an exception is thrown on the same line of code. In this case, Visual Studio 2015 will display following dialog.

2

Its showing that a NullReferenceException has been caused on the same line but without much details about which object is responsible for the exception. Clicking on View Detail here brings up following dialog.

3

This dialog is also not telling us either about the object causing the exception. Obviously if you are debugging this code, you can inspect all related objects to determine the culprit but this is exactly where Visual Studio 2017 Exception Helper can save some of that time.

Same program when debugged under Visual Studio 2017 presents following dialog.

4.PNG

As you can see in this case, Visual Studio 2017 is clearly showing that its the product.Detail object that returning a null causing the exception. Isn’t it great and a time saver?

There are many other tit-bits that you can do with this Exception Helper in Visual Studio 2017 that I will continue to explore in my upcoming blog posts.

Until next, happy debugging!!

Posted in CodeProject, Visual Studio 2017 | Leave a comment

Visual Studio 2017 – Run To Click

Visual Studio 2017 has provided several key improvements in Debugging experience. One of them is called “Run To Click”. “Run to cursor” has been a familiar experience for all developers for many years. This provided a convenient way of running your program to the cursor location using a short-cut such as Ctrl+F10. Of course, same could also be achieved by adding a break-point on the line of code and hitting F5. Of course adding a break-point meant that your program execution could be stopped at the same line again. However both of these approaches have their own “latencies” that Visual Studio team decided to address in Visual Studio 2017. Let’s say your are debugging your program, during that you may notice green Glyph appearing as shown in red rectangle in picture below.

1

Hovering the cursor on the glyph shows “Run execution to here” tooltip as shown below.

1a

If you click on the glyph here, the program execution will continue and stop at this line. In this example, user will be first prompted to enter the length of Fibonacci series. Let’s say user enter a number 5 here.

2

Once user hit enter key, the execution will stop on the same line.

3

That’s great. It certainly saves some time when debugging. But wait, things can be even better. From the code, we can see that the GenerateFibonacciSeries method will be called next within the if statement. Let’s say I want to debug the loop within that method. All I need to do is to take my mouse to that line and you will see same green glyph there as shown below.

4

Just as the name of feature says, you just “Run to Click” and it will take you right there.

5

As you can see from the Local window, the program execution stopped at the first iteration in the loop. If needed, you can click on the green glyph again on same line and execution will stop on the second iteration of same loop.

6

Until next, happy debugging!!

Posted in CodeProject, Visual Studio 2017 | Leave a comment

C# 7.0 – Deconstruct in a C# Class

In my blog, I explained how a Tuple could be consumed via deconstruction. Its important to know that this concept is not specific to Tuples. In today’s post I will show how that concept could be applied to a regular class.  Let’s say you have following Employee class.

class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string MiddleName { get; set; }
}

You can add a Deconstruct method to this class that accepts out parameters that could be initialised in the method for consumption by deconstruction. So let’s add a Deconstruct method as follows.

class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string MiddleName { get; set; }

  public void Deconstruct(out string firstName, out string lastName)
  {
     firstName = this.FirstName;
     lastName = this.LastName;
  }
}

Now this class can be consumed as follows using deconstruct syntax.

static void Main(string[] args)
{
    var employee = new Employee() { FirstName = "John", LastName = "Doe", MiddleName = "Sue" };
 
    (string firstName, string lastName) = employee;
    Console.WriteLine($"First Name = {firstName} Last Name = {lastName}");
}

Output of this will be as follows.

Capture

Your class can expose more then one Deconstruct method with varying number of parameters, so that it can be consumed appropriately.  Code below shows same Employee class with two Deconstruct methods.

class Employee
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string MiddleName { get; set; }

 public void Deconstruct(out string firstName, out string lastName)
 {
    firstName = this.FirstName;
    lastName = this.LastName;
 }
 public void Deconstruct(out string firstName, out string lastName, out string middleName)
 {
    firstName = this.FirstName;
    lastName = this.LastName;
    middleName = this.MiddleName;
 }
}

Now you can consume the object using deconstruction in similar manner as shown below.

static void Main(string[] args)
{
  var employee = new Employee() { FirstName = "John", LastName = "Doe", MiddleName = "Sue" };
 
  (string firstName, string lastName, string middleName) = employee;
  Console.WriteLine($"First Name = {firstName} Last Name = {lastName} Middle Name = {middleName}");
}

The output now contains the Middle Name as well.

Capture

Until next, happy debugging.

 

Posted in Uncategorized | Leave a comment

C# 7.0 – Tuples Re-Engineered

Tuples have been around for quite sometime as a convenient way of returning more than one value from a method. Even though Tuples were quite easy to use but from code-readability perspective, there were certainly room for improvement. In C# 7.0, team Microsoft made lot of enhancements with introduction of Tuple Types and Tuple Literals. Let’s review those changes. A typical use of Tuple could look as follows.

static void Main(string[] args)
 {
    Tuple<int, string> info = GetInfo();
    Console.WriteLine($"{info.Item1} -> {info.Item2}");
 }

static Tuple<int, string> GetInfo()
 {
    return new Tuple<int, string>(1, "Joe");
 }

With the new syntax, the GetInfo method can be rewritten as follows. This is basically Tuple Literals where the data items are comma separate within the parenthesis. Also notice that the function return type is using same syntax.

static (int, string) GetInfo()
{
    return (1, "Joe");
}

On the caller side, you can still use old way of calling the method.

static void Main(string[] args)
{
    (int, string) info = GetInfo();
    Console.WriteLine($"{info.Item1} -> {info.Item2}");
}

Of course, Type inference could still be applied as well when calling the method.

static void Main(string[] args)
{
    var info = GetInfo();
    Console.WriteLine($"{info.Item1} -> {info.Item2}");
}

As shown in image below, the tool-tip is showing appropriate type has been inferred.

1

However, the  declaration of Tuple without any variable names doesn’t make code easily readable and understandable. Good news is there is a better way. The code snippet below shows a newer version of GetInfo method. In this case, we have used the names of the variables which makes it much easier to understand as to what data is returned from this method.

static (int id, string name) GetInfo()
{
   return (id:1, name:"Joe");
}

These variables names can also be used in the Caller side as shown below.

static void Main(string[] args)
 {
   var info = GetInfo();
   Console.WriteLine($"{info.id} -> {info.name}");
 }

The type inference also shows these variable names as shown below.

2

When consuming the Tuples, there is even better way by what’s called “deconstructing” a tuple.  Code snipping below shows that the value returned by GetInfo method does not have a variable name but its consumed in the Console.WriteLine method just the tuple variable names.

static void Main(string[] args)
{
    (int id, string name) = GetInfo();
    Console.WriteLine($"{id} -> {name}");
}

For the var junkies out there, the code snippet above can be used as follows also.

static void Main(string[] args)
{
   (var id, var name) = GetInfo();
   Console.WriteLine($"{id} -> {name}");
}

And to simplify it even further, you can do as follows just with one var.

static void Main(string[] args)
{
   var ( id, name) = GetInfo();
   Console.WriteLine($"{id} -> {name}");
}

Until next, happy debugging!!

Posted in .NET, CodeProject, Visual Studio 2017 | Leave a comment

Visual Studio 2017 – Simplified Object Initialization

Visual Studio 2017 introduced code refactoring to simplify object initialization. Let’s say we have following class called Bar.

1

And here is how this class is consumed.

2

Notice the Gray dots under the new keyword in this picture. This is an indication that there is some code refactoring available. In order to view it, just click the Ctrl+. and it will bring up following pop-up.

3

As you can see in this image, the suggested change is to initialize the BarId and BarName properties using Object Initializer. If you choose to apply this suggestion, the updated code will look as follows.

4

Until next, happy debugging.

 

Posted in Uncategorized | Leave a comment

Visual Studio 2017 – Add Braces

Visual Studio 2017 code refactoring improvements also made it easy to adapt to some best practices. One of those is adding braces around your code blocks. Let’s say you have code as follows. There are quite a few if -else conditions handled here but not wrapping this type of code in braces can generate lot of interesting discussion.

0

My goal is not to re-ignite that type of discussion here again because there is enough already available on internet. What I would like to point out here the new refactoring improvements that can make adding those best practices a little easier. If you look closely, you will notice those gray dots showing up under the if clauses as displayed in red rectangles in image below.

1

Those gray dots basically provide a hint that you can apply some code refactoring here using old friend Ctrl+. . Doing it will bring up following dialog for adding the braces. As you can see in blue rectangle in image below, you get the option to apply this in your Document, Project or entire Solution.

2

Let’s say I choose Document here. Doing this will bring up following dialog with preview and a chance to fine-tune where you exactly want to apply this.

3

At this point, if you hit Apply button, the changes will appear in your code as shown below.

4

Until next, happy debugging.

 

Posted in Visual Studio 2017 | Leave a comment

Visual Studio 2017 – Structure Visualizers

Structure Visualiser is one of the  popular features from Productivity Power Tools in 2013 and 2015 versions. Good news is that with Visual Studio 2017, the Structure Visualiser comes out of box without need to install anything.

In case you don’t know what is the Structure Visualiser, it is defined as follow here:

Structure Visualizer adds visual cues to syntactically signify blocks of code. The blocks allow you to quickly figure out the scope of a class, method and many other code scopes. Hovering over the block visual cues brings up a preview tooltip to help you visualize the scope you’re in.

To understand this, let’s inspect the picture below where you can see that the class Foo is visible on the screen. However, the class above Foo is not visible on the screen although this class methods GetBarId and SetBarId are visible.

In simplest terms, Structure Visualiser provides an easy way to view the name of class or methods partially visible without need to scroll anywhere else on the screen. On the left side, you can see vertical dotted lines that could be used to get that type of information. For example if you hover your mouse over the middle vertical line, it shows the namespace and class name as shown below.

Similarly if you hover mouse over the vertical dotted line, it shows the method name as shown below.

If you don’t want to see these lines, it can be turned on-off from “Show structure guide lines” available  Tools -> Options -> Text Editor -> General menu item as shown below.

Until next, happy debugging!

 

Posted in Visual Studio 2017 | Leave a comment