Lately I seem to run into a situation very frequently where I want to write something like the following:
var x =
condition1 ? value1 :
condition2 ? value2 :
condition3 ? value3 :
condition4 ? value4 :
throw new InvalidOperationException();
Suppose the conditions are not simply constants so I can’t use switch
, but they are not complex enough expressions to warrant saying that ?:
is too unreadable.
Of course the above construct doesn’t compile because throw
is a statement, not an expression. Therefore, I considered writing a method that does exactly that:
/// <summary>Throws the specified exception.</summary>
/// <typeparam name="TResult">The type to return.</typeparam>
/// <param name="exception">The exception to throw.</param>
/// <returns>This method never returns a value. It always throws.</returns>
public static TResult Throw<TResult>(Exception exception)
{
throw exception;
}
[...]
var x =
condition1 ? value1 :
condition2 ? value2 :
condition3 ? value3 :
condition4 ? value4 :
Ut.Throw<MyType>(new InvalidOperationException());
Are there any problems with this approach that I’m not seeing?
throw
expressions are legal in?:
expressions in C++. \$\endgroup\$