Today a follow-up to my 2010 article about the meaning of the
is operator. Presented as a dialog, as is my wont!
I’ve noticed that the
is operator is inconsistent in C#. Check this out:
string s = null; // Clearly null is a legal value of type string
bool b = s is string; // But b is false!
What’s up with that?
Let’s suppose you and I are neighbours.
Um… ok, I’m not sure where this is going, but sure.
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.