I found a case where I have some code that I believe to be unreachable and is not detected. No warning is issued neither by the compiler nor by Visual Studio.
Consider this code:
enum Foo { A, B, C } class Bar { public Foo type; } static class Program { private static void Main() { var bar = new Bar { type = Foo.A }; if (bar.type == Foo.B) { Console.WriteLine("lol"); } } }
Obviously, the program will not print out "lol" because the condition in the if statement is false. I do not understand why a warning is not issued for the unreachable code though. My only hypothesis is that that could potentially be reachable if you have a race condition in a multi-threaded program. Is this correct?
In computer programming, unreachable code is part of the source code of a program which can never be executed because there exists no control flow path to the code from the rest of the program.
Just add a premature return while working on the code in the function or the code calling the function.
While some simple cases of unreachable code can be detected by static analysis (typically if a condition in an if statement can be determined to be always true or false), most cases of unreachable code can only be detected by performing coverage analysis in testing, with the caveat that code reported as not being ...
Static analysis can only do so much, and it will only mark code as unreachable if it can prove that a value cannot be changed. In your code, what happens inside Bar
is out of the scope of the method flow and can't be statically reasoned about. What if Bar
's constructor launches a thread that sets the value of type
back to B
? The compiler can't know about it, because, again, the internals of Bar
aren't scoped to the method.
If your code was checking the value of a local variable, then the compiler could know if there was no way for it to change. But that's not the case here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With