Handling switch statement
-
07-03-2021 - |
Question
What's the preferred way to handle the following case:
switch (numberOfActualBytes)
{
case 1: return something1;
case 2: return something2;
case 3: return something3;
case 4: return something4;
}
I know for certain that numberOfActualBytes
due to the used contract is in range 1-4
.
How should I write the code that doesn't result in not all code paths return a value
error?
I suspect I should throw some exception at the end of this function or in default switch case
, but probably there is a better solution.
Solution
I prefer to throw an out-of-range exception in the default
case if the application can be expected to uphold the 1..4 contract. The exception reflects the expectation on the caller that they will give me good data.
If your compiler cannot figure out that the default
case solves the not all code paths, then put the return
after the switch
. But the c# compiler will get it right.
OTHER TIPS
default: return error_code
would be my solution.
I would probably do something like this.
declare temp_something = a default value; //Used to check for error.
switch (numberOfActualBytes)
{
case 1: temp_something = something1; break;
case 2: temp_something = something2; break;
case 3: temp_something = something3; break;
case 4: temp_something = something4; break;
}
return temp_something;
Wouldn't this do the same?