Returning now to the subject we started discussing last time on FAIC: sometimes the compiler can know via static analysis[1. That is, analysis done knowing only the compile-time types of expressions, rather than knowing their possibly more specific run-time types] that an
is operator expression is guaranteed to produce a particular result.
As I said last time, that was a pretty easy puzzle. The solution is: either
FooBar or the type of local variable
x can be a type parameter:
It is possible for a program with some local variable
bool b = x is FooBar;
to assign true to
b at runtime, even though there is no conversion, implicit or explicit, from
FooBar allowed by the compiler! That is to say that
FooBar foobar = (FooBar)x;
would not be allowed by the compiler in that same program.
Can you create a program to demonstrate this fact?
This is not a particularly hard puzzle but it does illustrate some of the subtleties of the
is operator that we’ll discuss in the next episode.
(Note: not to be confused with Inheritance and Representation.)
I get a fair number of questions about the C# cast operator. The most frequent question I get is:
short sss = 123;
object ooo = sss; // Box the short.
int iii = (int) sss; // Perfectly legal.
int jjj = (int) (short) ooo; // Perfectly legal
int kkk = (int) ooo; // Invalid cast exception?! Why?
Why? Because a boxed T can only be unboxed to T (or
Nullable<T>.) Once it is unboxed, it’s just a value that can be cast as usual, so the double cast works just fine.