Directly throw Exception as an Expression – Throw expressions in C# 7.0

Directly throw Exception as an Expression – Throw expressions in C# 7.0

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.

ExceptionHope this helps

Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.