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

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

    Join 2,484 other followers

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:

    System.Diagnostics.Debug.Fail("Unreachable code reached");
    throw new InvalidOperationException();


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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: