tags:

views:

60

answers:

3

Hi All, 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 :-)

+2  A: 

Check out Jon Skeet's description of the new keyword usage. Because a is cast as A, you are calling A's method, which cannot be overridden. B just happens to have a method with the same name.

Yuriy Faktorovich
thnx for d link
Wondering
+2  A: 

When you hide a base-class method using the new keyword, the call is resolved by the compiler, not at runtime.

Therefore, when you write a.Test, the compiler emits a call to the Test method on the A class. Even though the a variable happens to refer to a B instance, the compiler doesn't care, and it still calls the version on A.

When you call a virtual method, the compiler emits a callvirt instruction 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 type B, and will see that B overrides the method and call the overridden version.

SLaks
That means this is Compile time vs Runtime..I got your point , thnx.
Wondering
A: 

Basically, once you create additional classes which derive from either A or B, you'll find that calling base.Test() will call A's version for those classes which override rather than new and those which derive from B will have B's version called but NOT A's.

Jesse C. Slicer