For some reason, M1()
causes a compiler error, while M2()
, which does the same thing, causes no error. Any idea why?
Using false ==>
good find, here is what I think. note that this is definitely something that could be fixed, but I'm trying to find a reasoning for it. note that this is not accurate answer. just saying!
its not just false ==
that causes this problem, but also == true
causes i
to become unusable in either branch, so I went ahead and wrote this.
var x = obj is int i;
if(x) Console.WriteLine(i);
you get the same error. as you can see if x
is true then i
should be initialized, right? unless you start to muck with x
value! here x
is not constant therefor we can not guarantee that x
always remains true before executing if statement.
how ever compiler can compute constant values and expressions at compile time. I'm not sure what is happening here but what I think is
if((obj is int i) == false)
here ==
operator puts a gap between result of pattern matching and evaluating if statement, hence the error. I don't know why !
operator works fine, maybe they optimized that part but forgot to optimize this? ;)
I think this relates to Semantic Analysis phase of compiler, its job is to validate meaning of your code and determine how its executed, if there is something wrong, if there is possibility of undefined behavior or there is something totally meaningless, it fails and you get compile time error. read more about Phases of Compiler Design