How the new keyword works in the output class

I got some confusion with the new keyword, everything works fine when I use virtual and redefinition, but slightly different from the new ones (I think something is missing)

 class A
{
    public virtual void Test()
    {
        Console.WriteLine("I am in A");
    }
}

class B:A
{
    public override void Test()
    {
        Console.WriteLine("I am in B");
    }
}


class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        b.Test(); //I am in B
        A a = new B();
        Console.WriteLine(a.GetType()); // Type-B
        a.Test(); //I am in B
       Console.ReadKey();
    }
}

}

Now with a new

class A
{
    public  void Test()
    {
        Console.WriteLine("I am in A");
    }
}

class B:A
{
    public new void Test()
    {
        Console.WriteLine("I am in B");
    }
}


class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        b.Test(); //I am in B
        A a = new B();
        Console.WriteLine(a.GetType()); //B
        a.Test(); // I am in A ? why?
       Console.ReadKey();
    }
}

according to MSDN. When a new keyword is used, new class members are called instead of replaced base classes. These base class members are called hidden members, also GetType () shows the type as B. Therefore, when I am wrong, it seems like a silly mistake :-)

+3
source share
3 answers

new, , .

, a.Test, Test A. , A B, , - A.

, callvirt, . , B , B .

+2

Jon Skeet n new. a A, , . B .

+2

, , A B, , base.Test() A , override, new , B, B, NOT A.

0

Source: https://habr.com/ru/post/1733935/


All Articles