C# 6.0 Features

Expression Bodied Methods

Old way

public string FullName 
{
    get
    {
        return FirstName + " " + LastName;
    }
}

New way

public string FullName => FirstName + " " + LastName;

Conditional Access Operator

Old way

object.property1.property2.leafvalue

if (object != null) {
    if (object.property1 != null) {
        if (object.property2 != null {
            return object.property1.property2.leafvalue;
    }
}

New way

object?.property1?.property2?.leafvalue

//?. has to be on every level

Auto-Property Initializers

Old way

public class ClassWithDefaultValue
{
    public int DefaultValueForProperty { get; private set; }

    public ClassWithDefaultValue() 
    {
        DefaultValueForProperty = 256;
    }
}

New way

public class ClassWithDefaultValue
{
    public int DefaultValueForProperty { get; private set; } = 256;
}

await in Catch block

New way

public static async void CallerMethod()
{
    try
    {
        throw new Exception();
    }
    catch (Exception)
    {
        Console.WriteLine("Before catch await " + Thread.CurrentThread.ManagedThreadId);
        await TestAsync();
        Console.WriteLine("After catch await " + Thread.CurrentThread.ManagedThreadId);
    }
    finally
    {
        Console.WriteLine("Before finally await " + Thread.CurrentThread.ManagedThreadId);
        await TestAsync();
        Console.WriteLine("After finally await " + Thread.CurrentThread.ManagedThreadId);
    }
}

exception filters

Old way

static void Main()
{
    try
    {
        Foo.DoSomethingThatMightFail(null);
    }
    catch (MyException ex)
    {
        if (ex.Code == 42)
            Console.WriteLine("Error 42 occurred");
        else
            throw;
    }
}

New way

try {
// Do stuff
} catch (Exception e) when ( (DateTime.Now.DayOfWeek == DayOfWeek.Saturday) || 
(DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) {
// Swallow
}

using StaticClass;

Old way

using System;


Console.WriteLine("Line 1");
Console.WriteLine("Line 2");

New way

using System;
using static System.Console;


WriteLine("Line 1");
WriteLine("Line 2");

String interpolation

Old way

string.Format("Witaj {0}. Dzisiaj jest {1}", name, DateTime.Now);

New way

$"Witaj {name}. Dzisiaj jest {DateTime.Now}"

nameof

Old way

if (name == null) throw new ArgumentNullException("name");

New way

if (name == null) throw new ArgumentNullException(nameof(name));

Use them...

...but do not overuse!

Questions?

C# 6

By Pawel Lukasik