Tuesday, June 24, 2008

C# Puzzle No.8 (beginner)

It is interesting to note what dilemmas the compiler has to actually resolve during the compilation. In the code below there are two possibilities : the compiler will either pick the method from the base class having the same signature or the method from actual class for which the conversion of the parameter is required.

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 );
  }
Could you explain the compiler behaviour without running the code?

6 comments:

lukasz said...

I think that "int"-version will be executed (class A)

public void Foo( int n )

I didn`t run the code. The only explanation I have in mind is that System.Int32 is the explicit type for this operation:

var a = 5;

Soo I guess also for this one:

method(5) - will run method(int arg), not (double arg) even if in base class.

Actually in this one, existing int-like method in base class doesn`t really matter (these are not related like you said)

I hope I`m right

Wiktor Zychla said...

I guess you should try to run the code. I bet you'll be surprized.

Venu Babu Pavuluri said...

may I know when can I expect A::Foo method will be called?

Wiktor Zychla said...

the B::Foo( double ) will be called, even if the A::Foo( int ) provides a better match for the argument.

the compiler gives the priority to methods from the same class and when it finds a method with no loss of precision for paramters, it will pick up such method in favor of any method with better matching but from base class.

Mrityunjay said...

I think B::Foo( double ) will be called. Because Class B Override Class A.

J Doyle said...

Even explicitly passing a variable of type int will still result in Foo from B being called. I can see how debugging this sort of thing could be an enormous pain.