Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to throw an exception using short hand condition operator? c#

I am trying to use the short hand operator to check a condition in order to throw an exception.

throw (result == false) ? new Exception("Result is false.") : null;

The lines following the above line, I receive an "unreachable code detected error".

I'm thinking that if I "throw null" if the condition is not met, it is still throwing an exception.

Any better way to do this short hand?

like image 982
gp80586 Avatar asked Dec 08 '22 07:12

gp80586


1 Answers

As far as I know, you can't do this because you are throwing either an exception or a null and in either case the code below is always unreachable. You could simply do this on one line:

if (!result) throw new Exception("Result is false.");

This even ends up being less typed characters

like image 90
vane Avatar answered Dec 11 '22 07:12

vane