c# – What should I do when I am forced to write unreachable code? – Stack Overflow
Posted by jpluimers on 2014/09/09
Bosak posted an interesting piece of code on StackOverflow last year. His particular code was in C#, but it does not matter what kind of compiler you use:
Sometimes a compiler will complain about unreachable code, for instance when it thinks a function never returns a value.
But you know the program logic does.
Simple solution: When you have code that never should be reached: throw an appropriate exception.
public static int GetInt(int number)
{
int[] ints = new int[]{ 3, 7, 9, int.MaxValue };
foreach (int i in ints)
if (number <= i)
return i;
return int.MaxValue; //this should be unreachable code since the last int is int.MaxValue and number <= int.MaxValue is allways true so the above code will allways return
}
The last return could be replaced like this, as proposed by Matt Houser:
#if DEBUG
System.Diagnostics.Debug.Fail("Unreachable code reached");
#endif
throw new InvalidOperationException();
–jeroen
via c# – What should I do when I am forced to write unreachable code? – Stack Overflow.






Leave a comment