C# version 7.0 introduced a new feature or we can say more flexible to throw the exceptions in Lambda expressions. Before seeing this, we know what we can do earlier in C# 6.0.
Earlier up to C# 6.0, If you want to throw an exception we need to create a separate method and call that in respective expressions as follows,
- public void ThrowingExceptionsInExpressionsOld()
- {
- string obj = null;
- string noException = obj ? ? RaiseException();
- }
- public string RaiseException()
- {
- throw new Exception("Object is null");
- }
In the above code, we are trying to raise an exception via a new method in null coalescing expression. Now, from C# 7.0, we don't need to implement any additional method to raise an exception as above, instead, we can use direct throw statement in the expression. Following is the simplified code in C# 7.0.
- public void ThrowingExceptionsInExpressions()
- {
- string obj = null;
- string noException = obj ? ?
- throw new Exception("Object is null");
- }
The same way we can have a throw exceptions in Expression Bodied Constructors, Finalizers and Properties as well as while using conditional operators as shown below.
- string[] names = {};
- string firstName = names.Length > 0 ? names[0] : throw new ApplicationException("Cannot set a default name");
As these changes doesn't effect much at runtime, but these features will improve readability and also simplifies the development.
You can see complete code here in GitHub.
Happy Coding :)