0

The question: there is two classes, A and B

public abstract class A
{
    public A()
    {
        Console.WriteLine("A");
    }
    public virtual void Fun()
    {
        Console.WriteLine("A.Fun()");
    }
}
public class B : A
{
    public B()
    {
        Console.WriteLine("B");
    }
    public new void Fun()
    {
        Console.WriteLine("B.Fun()");
    }

}

If run:

    public void Main()
    {
        A a = new B();
        a.Fun();
    }

the output is:

A
B
A.Fun()

How to explain this result, I know it has something to do with abstract and suclassing, but I don't know how to explain. Please help.

JimZ
  • 1,182
  • 1
  • 13
  • 30

1 Answers1

8

You need to differentiate between new and override:

  • new: This does not override or touch the inherited base method. The method in B marked as new is only called when you call it on an object of type B (e.g. ((B)a).Fun()), but not when calling an instance of type B mapped to an object of type A. Can be used on any method (i.e. "hiding the base method").
  • override does touch the inheritance and the base function is really overriden. a.Func() will call the method defined in B. Can only be used on base methods marked as virtual.
aevitas
  • 3,753
  • 2
  • 28
  • 39
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113