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?
Foo.A
could potentially be equal toFoo.B
– AmnesiaBar
class modifies the value itself. That might not be the case in your example but certainly a possibility in a real world application. – Duckint x = M(); if (x == 123.456) { /* unreachable */ }
The comparison is legal becausex
is convertible to double, and the comparison will always be false no matter what the value of x is. The compiler isn't smart enough to deduce that, and is not required by the specification to be that smart. If you're in the habit of writing unreachable code then get in the habit of using a code coverage tool. – Farthingint x = M(); if (x * 0 != 0) { ... }
as unreachable, reasoning that any int times zero was zero, and so the condition was false. Though that reasoning was correct, that rule is found nowhere in the specification and therefore was a bug in the compiler which I fixed. Since C# 3.0 the compiler has correctly-according-to-the-specification treated the consequence of anif
as unreachable only when the condition is false and involves only constant expressions. – FarthingFoo.type
? It’s not a local variable, it’s a field in some object. – Touraneif
is unreachable only if the condition is constant false, and constant expressions do not contain variables. – Farthing