Home

Throwing C# Expressions

|
Updated:  
2018-01-30 12:26:56
|
C# 2010 All-in-One For Dummies
Explore Book
Buy On Amazon
C# versions prior to 7.0 have certain limits when it comes to throwing an exception as part of an expression. In these previous versions, you essentially had two choices. The first choice was to complete the expression and then check for a result, as shown here:

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();

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Bill Sempf is a seasoned programmer and .NET evangelist specializing in .NET applications.

Chuck Sphar is a programmer and former senior technical writer for the Visual C++ product group at Microsoft.