Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 525
SinisterMJ Avatar asked Dec 02 '22 19:12

SinisterMJ


1 Answers

The best approach would be to disable the warning at the top of the file:

#pragma warning disable 0162

An alternative is converting your const into a static readonly.

private static readonly FlyCapture2Managed.PixelFormat f7PF = 
                        FlyCapture2Managed.PixelFormat.PixelFormatMono16;

However, if performance is important for your code, I would suggest keeping it a const and disabling the warning. Although const and static readonly are functionally equivalent, the former allows better compile-time optimizations that might be otherwise lost.

like image 138
Douglas Avatar answered Jan 03 '23 11:01

Douglas