The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

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.

[sourcecode language=”csharp”]
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
}
[/sourcecode]

The last return could be replaced like this, as proposed by Matt Houser:

[sourcecode language=”csharp”]
#if DEBUG
System.Diagnostics.Debug.Fail("Unreachable code reached");
#endif
throw new InvalidOperationException();
[/sourcecode]

–jeroen

via c# – What should I do when I am forced to write unreachable code? – Stack Overflow.

Leave a Comment

 

Discover more from The Wiert Corner - irregular stream of stuff

Subscribe now to keep reading and get access to the full archive.

Continue reading