HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpModerate

What’s your opinion on a Throw() method?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
throwyourwhatmethodopinion

Problem

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:

/// Throws the specified exception.
/// The type to return.
/// The exception to throw.
/// This method never returns a value. It always throws.
public static TResult Throw(Exception exception)
{
    throw exception;
}

[...]

var x =
    condition1 ? value1 :
    condition2 ? value2 :
    condition3 ? value3 :
    condition4 ? value4 :
    Ut.Throw(new InvalidOperationException());


Are there any problems with this approach that I’m not seeing?

Solution

I would avoid using such statement. It doesn't seem to be a right place for this construction inside ?: operators and I do not see major benefits in using it. I would consider using following options:

1)

Type variable;
if (condition1) variable = value1;
else if (condition2) variable = value2;
...
else throw new InvalidOperationException();


This has a disadvantage that in each line you have variable = but anyway compiler will let you know if you haven't initialized variable value before using it so it won't bother me much.

2) Also if your value1, value2, etc cannot be null then I would consider using this:

var variable = 
    condition1 ? value1 :
    condition2 ? value2 :
    condition3 ? value3 :
    condition4 ? value4 :
    null;
if (variable == null) throw new InvalidOperationException();


P.S.: Of course I cannot be sure without knowing the context but if you have to write such statements frequently then it already seems to be wrong for me, maybe something may be changed on higher level?

Code Snippets

Type variable;
if (condition1) variable = value1;
else if (condition2) variable = value2;
...
else throw new InvalidOperationException();
var variable = 
    condition1 ? value1 :
    condition2 ? value2 :
    condition3 ? value3 :
    condition4 ? value4 :
    null;
if (variable == null) throw new InvalidOperationException();

Context

StackExchange Code Review Q#1760, answer score: 18

Revisions (0)

No revisions yet.