An "is" operator puzzle, part one

An "is" operator puzzle, part one

Rate This
  • Comments 21

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;

    bool b = x is FooBar;

    Console.WriteLine(b);

    FooBar foobar = (FooBar)x;

  • namespace IsConsoleApplication

    {

       class Program

       {

           static void Main(string[] args)

           {

               var x = new object();

               var b = x is FooBar;

               var fooBar = (FooBar)x;

           }

           class FooBar

           {

           }

       }

    }

    '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...

Page 2 of 2 (21 items) 12