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();
A a = new B();
Console.WriteLine(a.GetType());
a.Test();
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();
A a = new B();
Console.WriteLine(a.GetType());
a.Test();
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 :-)
source
share