C# 6 features

A look at some of the new C# 6 features (not in any particular order).

The Null-conditional operator

Finally we have a way to reduce the usual

if(PropertyChanged != null)
   PropertyChanged(sender, propertyName);

to something a little more succinct

PropertyChanged?.Invoke(sender, propertyName);

Read-only auto properties

In the past we’d have to supply a private setter for read only properties but now C# 6 allows us to do away with the setter and we can either assign a value to a property within the constructor or via a functional like syntax, i.e.

public class MyPoint
{
   public MyPoint()
   {
      // assign with the ctor
      Y = 10;
   }

   // assign the initial value via the initializers
   public int X { get; } = 8;
   public int Y { get; }
}

Using static members

We can now “open” up static class methods and enums using the

using static System.Math;

// Now instead of Math.Sqrt we can use
Sqrt(10);

String interpolation

Finally we have something similar to PHP (if I recall my PHP from so many years back) for embedding values into a string. So for example we might normally write String.Format like this

var s = String.Format("({0}, {1})", X, Y);

Now we can instead write

var s = $"({X}, {Y})";

Expression-bodied methods

A move towards the way F# might write a single line method we can now simplify “simple” methods such as

public override string ToString()
{
   return String.Format("({0}, {1})", X, Y);
}

can now be written as

public override string ToString() => String.Format("({0}, {1})", X, Y);

// or using the previously defined string interpolation
public override string ToString() => $"({X}, {Y})";

The nameof expression

Another improvement to remove aspects of magic strings, we now have the nameof expression. So for example we might have something like this

public void DoSomething(string someArgument)
{
   if(someArgument == null)
      throw new ArgumentNullException(nameof(someArgument));

   // do something useful
}

Now if we change the someArgument variable name to something else then the nameof expression will correctly pass the new name of the argument to the ArgumentNullException.

However nameof is not constrained to just argument in a method, we can apply nameof to a class type, or a method for example.

References

What’s new in C# 6