Wednesday, July 16, 2014

There are some diagnostics tricks which are the other new feature in C# 5.0 beyond async.

If one bolts...

, [CallerMemberName] string methodName = null, [CallerFilePath] string sourceFile = null,
      [CallerLineNumber] int lineNumber = 0

 
 

...into the end of a method or constructor signature, one will find that the methodName, sourceFile, and lineNumber variables get populated with details revealing what called the method. The name of the method will be in the methodName, the line number within the applicable file will be in lineNumber, and the full path to said file will be in sourceFile. Here is an example of usage. Let's say we have a class like so:

using System.Drawing;
namespace Security.Models
{
   public class Cat
   {
      public string Name { get; set; }
      public Color[] Colors { get; set; }
      
      public Cat()
      {
      }
      
      public Cat(string name, Color color)
      {
         Name = name;
         Colors = new Color[] {color};
      }
   }
}

 
 

If we were to refactor it to be like so...

using System.Drawing;
using System.Runtime.CompilerServices;
namespace Security.Models
{
   public class Cat
   {
      public string Name { get; set; }
      public Color[] Colors { get; set; }
      
      public Cat()
      {
      }
      
      public Cat(string name, Color color, [CallerMemberName] string methodName = null,
            [CallerFilePath] string sourceFile = null, [CallerLineNumber] int lineNumber = 0)
      {
         Name = name;
         Colors = new Color[] {color};
      }
   }
}

 
 

...and then:

  • make a new Cat in another place in code using the second constructor
  • set a breakpoint in Cat's second constructor
  • run the application until you hit the breakpoint

 
 

...we may mouse over the variables in the second constructor's signature to get at the data points. If you don't want to troubleshoot on the fly, perhaps these variables could be integrated into your logging.

No comments:

Post a Comment