Fabulous Adventures In Coding
Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric.
It is possible for a program with some local variable x:
bool b = x is FooBar;
to assign true to b at runtime, even though there is no conversion, implicit or explicit, from x to FooBar allowed by the compiler! That is,
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.
Eric, I can not wait to see a correct answer. Who is that lucky guy who guessed?
int x = 0;
static void Main(string args)
var x = new object();
var b = x is FooBar;
var fooBar = (FooBar)x;
'object' is compatible with 'FooBar', so b = true; but 'x' don't refer to a 'FooBar' when the type verification is performed in the type hierarchy.
Agree with Francisco Ruiz. 'is' operator is kind of compatible check, but not 'typeof x == "foobar"' thing
I agree with Stuart (comment #1).
> var x = new object();
> var b = x is FooBar;
> 'object' is compatible with 'FooBar', so b = true;
If b would indeed be true, I would need to fix a lot of code...