Everybody fails this test: C# strange inheritance

Hi, can someone explain the strange behaviour of c# . The output of this code below is:

"class B froma A". But more intuitive would be "class B from C". When one changes keyword override for new every things works like it supossed to (for me at least ).

using System;

namespace ConsoleApplication1

{

public class A

{

public A()

{

}

public virtual void Halo(C objectC)

{

Console.WriteLine("Class A");

}

}

public class B : A

{

public B()

{

}

public void Halo(A objectA)

{

Console.WriteLine("Class B from A");

}

public override void Halo(C objectC)

{

Console.WriteLine("Class B from C");

}

}

public class C : A

{

public C()

{

}

}

class Class1

{

[STAThread]

static void Main(string[] args)

{

C c = new C();

B objectB = new B();

objectB.Halo(c);

Console.ReadLine();

}

}

}




Answer this question

Everybody fails this test: C# strange inheritance

  • HaseXXXXXL

    Danger: language reference discussion coming :)

    The answer is in section 7.4.2 and section 7.5.5.1 of the C# language spec (2nd edition)

    The key point is in 7.5.5.1: "If N is applicable with respect to A (see 7.4.2.1), then all methods declared in a base type of T are removed from the set".

    The definitions of N, A, and T are in the surrounding text.

    Basically, if a method can be found in the derived type (compile time type, not runtime type) that matches the argument list, then the compiler does not search base classes.



  • ThrasherNYC

    If you compile that code with CodeAnalysis on, you will get the following warning:

    "Error CA1061 : Microsoft.Design : Change or remove B.Halo(A):Void as it hides a more specific base class method: A.Halo(C):Void."

    More information about that warning can be found here:

    http://msdn2.microsoft.com/en-us/ms182143.aspx


  • EDstyler

    Perhaps the C# binder prefers methods declared by the derived class over those declared by base classes (including those which are overidden). That would be my best guess, but it would be nice if someone would explain why it works this way.
  • Tesfaye

    Method overriden in derived class are considered by c# compiler as orginally defined on base class. so while matching argument method with overriden keyword is not considered if any method matches on the derived class(without override keyword).
  • Everybody fails this test: C# strange inheritance