C# 6.0 – my highlights

I just discovered two real highlights in C# 6.0. Some may call them syntactic sugar, but for me they are a great help keeping my source code clean and tidy.

String interpolation

Instead of the usual String.Format you can now use string interpolation, which allows you to write things like this:

int i = 5;
string s = $"The value of i is {i}";

You can even use the well known format specifiers like this:

double d = 2.5544;
string s = $"With only two decimals d is {d:F2}";

Null Conditional Operator

We all know constructs like this:

SomeClass v = null;
if (a != null && a.Field != null && a.Field.Value != null)
v = a.Field.Value.SomeClassValue;

You can understand this, but you can now write this much shorter:

SomeClass v = a?.Field?.Value?.SomeClassValue;

The ? operator will cause v to be null if any field along the path is null.

Love it!

Schreiben Sie einen Kommentar

Ihre E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.