Essential C# C# 7.0 Features  Suggest an edit

throw expressions

C# 7.0 allows throwing as an expression in certain places:

class Person
{
    public string Name { get; }

    public Person(string name) => Name = name ?? throw new ArgumentNullException(nameof(name));

    public string GetFirstName()
    {
        var parts = Name.Split(' ');
        return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
    }

    public string GetLastName() => throw new NotImplementedException();
}

Prior to C# 7.0, if you wanted to throw an exception from an expression body you would have to:

var spoons = "dinner,desert,soup".Split(',');

var spoonsArray = spoons.Length > 0 ? spoons : null;

if (spoonsArray == null) 
{
    throw new Exception("There are no spoons");
}

Or

var spoonsArray = spoons.Length > 0 
    ? spoons 
    : new Func<string[]>(() => 
      {
          throw new Exception("There are no spoons");
      })();

In C# 7.0 the above is now simplified to:

var spoonsArray = spoons.Length > 0 ? spoons : throw new Exception("There are no spoons");


Table Of Contents
22 Enum
25 GUID
70 C# 7.0 Features
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close