I am having some confusion with the new keyword,things work fine when I am using virtual and override , but a bit different with new(I think I am missing something)
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 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();
}
}
as per MSDN When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members, also the GetType() is Showing type as B.
So where I am going wrong, seems its a silly mistake 🙂
When you hide a base-class method using the
newkeyword, the call is resolved by the compiler, not at runtime.Therefore, when you write
a.Test, the compiler emits a call to theTestmethod on theAclass. Even though theavariable happens to refer to aBinstance, the compiler doesn’t care, and it still calls the version onA.When you call a virtual method, the compiler emits a
callvirtinstruction that tells the runtime to find the correct method to call based on the actual type of the instance. The runtime is aware that the instance is actually of typeB, and will see thatBoverrides the method and call the overridden version.