C# 7.0 – Throw expressions

C# 7.0 introduced throw expression, throwing exception has always been a statement and need to call a method to throw exception. Syntax is same as you’ve always used to throw exceptions difference is it can be also placed in the conditional expressions

With c# 7.0 exceptions can be thrown directly from within expression as shown below-

 public class ThrowExpressions
 {
 public static string ThrowExpressionMethod(string someString)
 {
 return string.IsNullOrWhiteSpace(someString) ? throw new ArgumentNullException("someString is empty") : someString;
 }
 }

 

 

 

 

C# 7.0 Numerical literals and OUT variables

Numeric literal syntax

Reading numbers makes it difficult to understand code. C# 7 has improvement done on the digit separator.

public static int IntegerLiterals()
 { return 1_000_000; }

public static double DoubleLiterals()
 { return 9_8_7.1_2_3; }

public static int BinaryLiterals()
 { return 0b0001_0000; }

 Console.WriteLine($" One Million : {NumericalLiterals.IntegerLiterals()}");
 Console.WriteLine($" Double : {NumericalLiterals.DoubleLiterals()}");
 Console.WriteLine($" Binary to Decimal : {NumericalLiterals.BinaryLiterals()}");

Output:

One Million : 1000000
Double : 987.123
Binary to Decimal : 16

 

Inline out variables

Earlier declaring out variables has to be done separately. Now this can be done in line as follows

public static int InlineOutVariables()
 {
 string input = "100";
 if (!int.TryParse(input, out int result))
 {
 return 0;
 }
 return result;
 }

You can declare out variable where you use it.  The declared out variables also leaks out of the if statement scope and used later.