In one of our previous post, Expression – Bodied Members in C# 7.0 , we have seen how C# 7.0 extended the expression bodied members features for several new members including constructor, destructor, property assessors etc. C# 7.0 also introduces throw expressions, using which you can now throw an exception along with expression-bodied members, conditional expressions or even null-coalescing operations. Let’s have a look how it works.
Throw expressions are the simplified ways to raise the exceptions, where you just need to throw it, based on the condition. Consider the same example that we used in the previous post Expression – Bodied Members in C# 7.0
class Student { private string studentName; // Expression – Bodied Constructor public Student(string name) => studentName = name; }
Now, in case you need to raise the exception here with the expression bodied method, you can take the following approach.
class Student { private string studentName; // Expression – Bodied Constructor -- Throw Exception public Student(string name) => studentName = name ?? throw new ArgumentNullException(); }
Similar, this works with Properties as well.
public string Name { get => studentName; set => studentName = value; }
In case you want to raise an exception while assign the value, you can simply do the following.
// Expression - Properties - Throw Exception public string Name { get => studentName; set => studentName = value ?? throw new ArgumentNullException(); }
All in all, Throw expressions helps you to write smaller code block and using same patterns of expression to raise the exception, internally, it works in a same way.
Hope this helps
Pingback: Dew Drop - July 31, 2017 (#2531) - Morning Dew
Pingback: Declare Out variable right at the point – Out variable in C# 7.0
Pingback: The week in .NET – Nuke, Warden.NET, .NET in Bangalore, and links! | .NET Blog
Pingback: Improve Code readability using Digit Separator in C# 7.0