April 14th, 2017  // Posted in C#

Release of Visual Studio 2017 not only introduced new productivity tools and improvements for the code editing experience, but also brought new version of C#.

Similar to the previous release – C# 6.0 – new release is not focused on a single flagship feature and introducing several smaller features. One of the most exiting of these features (at least for me) is out variables. Initially this feature was planned for 6.0 release but was cut shortly before the release.

Code which is similar to the following snipped is extremely common in all types of C# application:

public string ReformatDouble(string val)
{
   double x;

   if (double.TryParse(val, out x))
   {
      return $"{x:F4}";
   }

   return $"{x}";
}

Sometime out variable is not even needed, because the single propose of the code could be testing parsing of the value:

public bool IsDouble(string val)
{
   double x;
   return double.TryParse(val, out x);
}

With the new “out variable” feature this code can be significantly simplified:

public string ReformatDouble(string val)
{
   if (double.TryParse(val, out var x))
   {
      return $"{x:F4}";
   }

   return $"{x}";
}

One interesting point here is the scope of the variable. Unlike variable i defined in the following loop for (var i = 0; i < 10; i++) {}, x continues to exist even outside of if (…) {} construct.

When out variable is not needed, code can be simplified even more - variable can be discarded:

public bool IsDouble(string val)
{
   return double.TryParse(val, out _);
}

Happy parsing!

blog comments powered by Disqus