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 4,224 other subscribers

Archive for September 9th, 2014

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: Read the rest of this entry »

Posted in .NET, .NET 1.x, .NET 2.0, .NET 3.0, .NET 3.5, .NET 4.0, .NET 4.5, C#, C# 1.0, C# 2.0, C# 3.0, C# 4.0, C# 5.0, Development, Software Development | Leave a Comment »

 
%d bloggers like this: