Search code examples
c#unreachable-code

Unreachable code detected by using const variables


I have following code:

private const FlyCapture2Managed.PixelFormat f7PF = FlyCapture2Managed.PixelFormat.PixelFormatMono16;

public PGRCamera(ExamForm input, bool red, int flags, int drawWidth, int drawHeight) {
   if (f7PF == FlyCapture2Managed.PixelFormat.PixelFormatMono8) {
      bpp = 8;  // unreachable warning
   }
   else if (f7PF == FlyCapture2Managed.PixelFormat.PixelFormatMono16){
      bpp = 16;
   }
   else {
      MessageBox.Show("Camera misconfigured");  // unreachable warning
   }
}

I understand that this code is unreachable, but I don't want that message to appear, since it's a configuration on compilation which just needs a change in the constant to test different settings, and the bits per pixel (bpp) change depending on the pixel format. Is there a good way to have just one variable being constant, deriving the other from it, but not resulting in an unreachable code warning? Note that I need both values, on start of the camera it needs to be configured to the proper Pixel Format, and my image understanding code needs to know how many bits the image is in.

So, is there a good workaround, or do I just live with this warning?


Solution

  • You can replace the conditional with a Dictionary lookup to avoid the warning:

    private static IDictionary<FlyCapture2Managed.PixelFormat,int> FormatToBpp =
        new Dictionary<FlyCapture2Managed.PixelFormat,int> {
            {FlyCapture2Managed.PixelFormat.PixelFormatMono8, 8}
        ,   {FlyCapture2Managed.PixelFormat.PixelFormatMono16, 16}
        };
    ...
    int bpp;
    if (!FormatToBpp.TryGetValue(f7PF, out bpp)) {
        MessageBox.Show("Camera misconfigured");
    }