C# 6.0 + 7.0 features.

C# 6.0

Auto Property Initializers

public class Developer
{
public bool DrinksCoffee {get;set;} = true;
}

Dictionary Initializers

var devSkills = new Dictionary<string, bool>();

devSkills["C#"] = true;
devSkills["HTML"] = true;

var devSkills = new Dictionary<string, bool>() {
["C#"] = true,
["VB.NET"] = true,
["HTML"] = true
};

String Interpolation

string test = "test1" + "with " + test2 + " finished.";
string test2 = string.Fromat("{0} {1}, {2} @ {3}", test1, test3, test4, test5);

var testCsharp6 = $"{firstName} {middleName} {lastName} , {jobTitle} @ {Company}";

Null Conditional Operator

public string[] GenerateCoffeeOrder(Coffee[] favCoffee)
{
var order = favCoffee?.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

\?.\

  • “?” If the variable is null, then return null.
  • Otherwise execute whatever is after the “.”

Name of Expression

public string[] GenerateCoffeeOrder(Coffee[] favCoffee)
{
if (favCoffee == null)
{
throw new ArgumentNullException("favCoffee");
}

var order = favCoffee.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

public string[] GenerateCoffeeOrder(Coffee[] coffeeOrders)
{
if (coffeeOrders == null)
{
throw new ArgumentNullException(nameof(coffeeOrders));
}

var order = coffeeOrders.Select(x => $"{x.Name} - {x.Size}").ToArray();

return order;
}

Expression Bodied Functions & Properties

public class Coffee {
public string Name {get;set;}
public string Size {get;set;}
public string OrderDescription => $"{Name} - {Size}";
}

Exception Filters

catch (SqlException ex) when (ex.ErrorCode == -2)
{
return "Timeout Error";
}
catch (SqlException ex) when (ex.ErrorCode == 1205)
{
return "Deadlock occurred";
}
catch (SqlException)
{
return "Unknown";
}

catch (SqlException ex) when (HttpContext.Current.Identity.Name == "Boss Man" || DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday) {
// Do nothing
}

Static Using

public double GetArea(double radius)
{

return Math.PI * Math.Pow(radius, 2);
}

public double GetArea(double radius
{
return PI * Pow(radius, 2)
;

}

Await in Catch and Finally Blocks

Extension Add in Collection Initializers

C# 7.0

Improvements to the Tuple Class

var newTuple = new Tuple<string, decimal, bool>(Name: "A", OrderTotal: 123, IsVIP: true);

Inline output variable

if (int.TryParse("123", out var i)
{
    
}

Pattern matching in ‘switch’

public string SuggestAnAction2(Bird bird) {
    switch (bird):
    {
        case Magpie m when m.IsSwoopingSeason == true:
            return "Bring a helmet";
        case Magpie m when m.IsSwoppingSeason == false:
            return "Go for a stroll";
        case Budgie b:
            return $"Bring {b.FavouriteFood} for the walk";
        case null:
            throw new ArgumentNullException(nameof(bird));
        default:
            return "Do nothing"
    }
}