C# 7.0 - Throw expressions

C# 7.0 開始支援 Throw expressions。


三元運算中可以視需要直接丟出 exception。

1
2
3
...
this.FirstName = firstName == null ? throw new ArgumentNullException(nameof(firstName)) : firstName;
...


?? 運算式中也可以直接丟出 exception。

1
2
3
...
this.LastName = lastName ?? throw new ArgumentNullException(nameof(lastName));
...


Expression bodied member 也可以丟出 exception。

1
2
3
...
public override string ToString() => throw new NotImplementedException();
...


最後附上完整的測試範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Program
{
static void Main(string[] args)
{
var person = new Person("Larry", "Nung");
Console.WriteLine(person.ToString());
}
}
struct Person
{
public string FirstName { get; set; }
public string LastName { get; set; }

public Person(string firstName, string lastName)
{
this.FirstName = firstName == null ? throw new ArgumentNullException(nameof(firstName)) : firstName;
this.LastName = lastName ?? throw new ArgumentNullException(nameof(lastName));
}

public override string ToString() => throw new NotImplementedException();
}


Link