var myStrings = "One,Two,Three".Split(',');
var numbers = (myStrings.Length > 0) ? myStrings : null
if(numbers == null){throw new Exception("There are no numbers!");}
The second option was to make throwing the exception part of the expression, as shown here:
var numbers = (myStrings.Length > 0) ?
myStrings :
new Func<string[]>(() => {
throw new Exception("There are no numbers!"); })();
C# 7.0 and above includes a new null coalescing operator, ?? (two question marks). Consequently, you can compress the two previous examples so that they look like this:
var numbers = myStrings ?? throw new Exception("There are no numbers!");
In this case, if myStrings
is null, the code automatically throws an exception. You can also use this technique within a conditional operator (like the second example):
var numbers = (myStrings.Length > 0)? myStrings :
throw new Exception("There are no numbers!");
The capability to throw expressions also exists with expression-bodied members. You might have seen these members in one of the two following forms:
public string getMyString()
{
return " One,Two,Three ";
}
or
public string getMyString() => "One,Two,Three";
However, say that you don’t know what content to provide. In this case, you had these two options before version 7.0:
public string getMyString() => return null;
or
public string getMyString() {throw NotImplementedException();}
Both of these versions have problems. The first example leaves the caller without a positive idea of whether the method failed — a null return might be the expected value. The second version is cumbersome because you need to create a standard function just to throw the exception. Because of the new additions to C# 7.0 and above, it’s now possible to throw an expression. The previous lines become
public string getMyString() => throw new NotImplementedException();