1) According to my book, the is operator can verify that the expression E ( E is type ) can be converted to the target type only if E is either a reference transformation, or a box, or an unpack. Since in the following example, is does not check any of the three conversion types, the code should not work, but it:
long l; // EDIT - I forgot to add this line of code in my initial post int i=100; if (i is long) //EDIT - in my initial post I've claimed condition returns true, but it really returns false l = i;
2)
a)
B b; A a = new A(); if (a is B) b = (B)a; int i = bl; class A { public int l = 100; } class B:A { }
The above code always causes a compile-time error "Use of unassigned variable" . If the condition a is B evaluates to false , then b will not be assigned a value, but if the condition is true , then it will be. And thus, by allowing such a code compiler, there is no way to find out if using b in the code following the if is valid or not (because it doesn't know if a is B true or false ) but why would he know that? Intsead why can't runtime handle this?
b) But if instead they were dealing with non-reference types, then the compiler does not complain, although the code is identical. Why?
int i = 100; long l; if (i is long) l = i;
Thank you
source share