Saturday, January 09, 2016

You can use C# version 6 features right now, and how glorious they are!

Some of you may have heard of C# 6, the new version of the Microsoft .NET programming language, but what I am not certain about is that you know you can use it right now. I had expected that a new version of the language will be usable from the brand new upcoming fifth version of the .NET runtime, but actually no, you can use it right now in your projects, because the new features have been implemented in the compiler, in Visual Studio and, you have no idea how cool it is until you try, in ReSharper.

One might say: "Hell, I've seen these syntactic sugar thingies before, they are nothing but a layer over existing functionality. New version, my ass, I stick with what I know!", but you run the risk of doing as one of my junior developer colleagues did once, all red faced and angry, accusing me that I have replaced their code with question marks. I had used the null-coalescing operator to replace five line blocks like if (something == null) { ....

Let me give you some examples of these cool features, features that I have discovered not by assiduously learning them from Microsoft release documents, by but installing ReSharper - only the coolest software ever - who recommends me the changes in existing code. Let's see what it does.

Example 1: properties with getters and no setters

Classic example:
public int Count {
  get {
    return _innerList.Count;
  }
}

Same thing using C# 6 features?
public int Count => _innerList.Count;
Cool or what?

Example 2: null checking in a property chain

Classic example:
if (Granddaddy!=null) {
  if (Daddy!=null) {
    if (Child!=null) {
      return Grandaddy.Daddy.Child.SomeStupidProperty;
    }
  }
}

Same thing using C# 6 features?
return Grandaddy?.Daddy?.Child?.SomeStupidProperty;
Convinced yet?

Example 3: using the name of members as strings

Classic example:
public int Number {
  get { return _number; }
  set {
    if (_number!=value) {
      _number=value;
      OnPropertyChanged("Number");
      //with some custom code you could have used a better, but slower version:
      //OnPropertyChanged(()=>Number);
    }
  }
}

C# 6 version?
public int Number {
  get { return _number; }
  set {
    if (_number!=value) {
      _number=value;
      OnPropertyChanged(nameof(Number));
      // this assumes that we have a base class with a method called OnPropertyChaged, but we can already to things inline:
      PropertyChanged?.Invoke(this,new new PropertyChangedEventArgs(nameof(Number))
    }
  }
}

Example 4: overriding or implementing simple methods

Classic example:
public override string ToString() { 
  return string.Format("{0}, {1}", First, Second);
}

Now:
public override string ToString() => $"{First}, {Second}";

Example 5: exception filters

Classic example:
try {
  SomethingUnpredictable();
}
catch (Exception e) {
  if (e.InnerException!=null) {
    UnpackAndLogException(e);
  } else {
    throw;
  }
}

C# 6 version:
try {
  SomethingUnpredictable();
}
catch (Exception e) when (e.InnerException!=null) {
    UnpackAndLogException(e);
}

Example 6: using static

I don't particularly like this, but it can simplify some code when used right. Classic example:
return degrees*Math.PI/180;

C# 6 way:
//somewhere above:
using static System.Math;

return degrees*PI/180;

There are other more complex features as well, like special index initializers for Dictionary objects, await in catch and finally blocks, Auto-property initializers and Primary Constructors for structs. You can use all these features in any .NET version 4 and above. All you need is the new Roslyn compiler.

Enjoy the new features. I know I will!

0 comments: