In this article, I am going to discuss the Thrown Expression in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Expression Bodied Members in C# with examples. In C#, it is very easy to throw an exception in the middle of an expression.
Let us understand Thrown Expression in C# with an example.
In the above example, we are throwing an expression in the middle of the method by checking the condition. But with C# 7.0 now it is possible to throw an exception in the middle of an expression. Let’s rewrite the above program to throw an exception in the middle of the expression as shown below.
OUTPUT:

You can throw any type of exception in the middle of an expression like “IndexOutOfRangeException”, “NullReferenceException”, “OutOfMemoryException”, “StackOverflowException” and many other types of exception.
You can add exception throwing to expression-bodied members, null-coalescing expressions, and conditional expressions. Throw expressions are the way to tell the compiler to throw the exception under specific conditions like in expression bodied members or inline comparisons.
Thrown Expression in C# real-time example:
This below example uses a simple Employee class to demonstrate different situations where throw expression in C# can be used:
- auto-property initializer statement
- inline comparison using the operator “?”
- expression-bodied member
OUTPUT:

In the next article, I am going to discuss the Async Main in C# with some examples. Here, in this article, I try to explain Thrown Expression in C# step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.