IS operator behaving a bit strangely
Posted
by flockofcode
on Stack Overflow
See other posts from Stack Overflow
or by flockofcode
Published on 2010-06-14T19:32:00Z
Indexed on
2010/06/14
19:32 UTC
Read the original article
Hit count: 174
1) According to my book, IS
operator can check whether
expression E
(E is type
) can be converted to the target type only if E
is either a reference conversion, boxing or unboxing. Since in the following example IS
doesn’t check for either of the three types of conversion, the code shouldn’t work, but it does:
int i=100;
if (i is long) //returns true, indicating that conversion is possible
l = i;
2)
a)
B b;
A a = new A();
if (a is B)
b = (B)a;
int i = b.l;
class A { public int l = 100; }
class B:A { }
The above code always causes compile time error “Use of unassigned variable”
. If condition a is B
evaluates to false
, then b
won’t be assigned a value, but if condition is true
, then it will. And thus by allowing such a code compiler would have no way of knowing whether the usage of b
in code following the if
statement is valid or not ( due to not knowing whether a is b
evaluates to true
or false
) , but why should it know that? Intsead why couldn’t runtime handle this?
b) But if instead we’re dealing with non reference types, then compiler doesn’t complain, even though the code is identical.Why?
int i = 100;
long l;
if (i is long)
l = i;
thank you
© Stack Overflow or respective owner