C# Potential Interview Question…Too hard?

FlySwat picture FlySwat · Sep 30, 2008 · Viewed 35.3k times · Source

Without running this code, identify which Foo method will be called:

class A
{
   public void Foo( int n )
   {
      Console.WriteLine( "A::Foo" );
   }
}

class B : A
{
   /* note that A::Foo and B::Foo are not related at all */
   public void Foo( double n )
   {
      Console.WriteLine( "B::Foo" );
   }
}

static void Main( string[] args )
{
   B b = new B();
   /* which Foo is chosen? */
   b.Foo( 5 );
}

Which method? And why? No cheating by running the code.

I found this puzzle on the web; I like it and I think I'm going to use it as an interview question...Opinions?

EDIT: I wouldn't judge a candidate on getting this wrong, I'd use it as a way to open a fuller discussion about the C# and CLR itself, so I can get a good understanding of the candidates abilities.

Source: http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html

Answer

Jon Skeet picture Jon Skeet · Sep 30, 2008

I really wouldn't use this as an interview question. I know the answer and the reasoning behind it, but something like this should come up so rarely that it shouldn't be a problem. Knowing the answer really doesn't show much about a candidate's ability to code.

Note that you'll get the same behaviour even if A.Foo is virtual and B overrides it.

If you like C# puzzles and oddities, I've got a few too (including this one).