New C# v7 Features in Visual Studio 2017

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0

Visual Studio is the tool I use to do a lot of my developer work. VS 2017 was released on March 31, 2017 — probably a much better idea than releasing it the next day.

VS 2017 contains a new version of the C# language, version 7. As has been the case with the last couple of versions of C#, the v7.0 has a few new features that aren’t very useful, but are somewhat interesting. Three of the new features are local functions, an improved Tuple type, and inline declarations.

First, inline declarations. Consider this example:


static void Main(string[] args)
{
  int x = 3; int y = 4;  // C# 7
  GetSum(x, y, out int sum);
  Console.WriteLine("Sum = " + sum);
}

static void GetSum(int x, int y, out int sum)
{
  sum = x + y;
}

The GetSum() function/method has an out-parameter, sum. The corresponding out-variable in the calling statement is declared as it’s used. Prior to C# 7 you’d have to declare the corresponding out-variable before calling GetSum() like so:

int sum;  // standard way
int x = 3; int y = 4;
GetSum(x, y, out sum);
Console.WriteLine("Sum = " + sum);

Yawn. OK, next, local functions. In C# 7 you can now define a function inside another function. Here’s a dummy example:

static void Main(string[] args)
{
  string s = "black";
  LocalDemo(s);
}

static void LocalDemo(string s)
{
  string Foo(string str)
  {
    if (str == "white") return "good";
    else if (str == "black") return "bad";
    else return "neutral";
  }
  string t = Foo(s);
  Console.WriteLine(t);
}

Prior to C# 7 you couldn’t do this. Yawn. Next, improved an Tuple type:

static void Main(string[] args)
{
  int[] values = new int[] { 5, 9, 4, 0, 3, 6 };
  var (largest, smallest) = Extremes(values);  // System.ValueTuple
} 

static (int max, int min) Extremes(int[] values)  
{
  int mx = int.MinValue; int mn = int.MaxValue;
  for (int i = 0; i < values.Length; ++i)
  {
    if (values[i] > mx) mx = values[i];
    if (values[i] < mn) mn = values[i];
  }
  return (mx, mn);
}

Unfortunately this new Tuple type requires a reference to System.ValueTuple.dll which is external to VS, in GitHub. This doesn’t even merit a yawn. An external rogue dependency for a barely useful construction is not going to happen in any of my code.

The moral of the story is that C# is a mature, awesome programming language. There are no new features the language needs. Period. Based on my experience, when you work on any product, there’s a powerful urge to add new features. But there are diminishing returns and eventually there’s a point where new features aren’t useful, and arguably even make your product worse due to increased complexity.

Advertisements

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0