简体   繁体   中英

Difference between new and override in below scenario

I have code below -

 public class Class1
    {
        public virtual void Test1()
        {
            Console.WriteLine("This is class 1");
        }
    }

And

   public class Class2 : Class1
    {
        public override void Test1()
        {
            Console.WriteLine("This is class 2");
        }
    }

Now if I am calling -

 static void Main(string[] args)
    {
        Class1 obj = new Class2();
        obj.Test1();
        Console.ReadLine();
    }

Result : Method from Class2 is called.

But now I change code with New keyowrd

 public class Class1
    {
        public void Test1()
        {
            Console.WriteLine("This is class 1");
        }
    }

and

   public class Class2 : Class1
    {
        public new void Test1()
        {
            Console.WriteLine("This is class 2");
        }
    }

And calling the same way as I am calling above -

static void Main(string[] args)
        {
            Class1 obj = new Class2();
            obj.Test1();
            Console.ReadLine();
        }

But result is different, Result : method from Class1 is called.

Question 1 : Why result changed while using New keyword.

Question 2 : what actually this line of code is doing Class1 obj = new Class2();

I understand it is creating the object but then how it is different from

Class1 obj = new Class1();

The above scenario has confused me a lot of times and then I started remembering it, that's how it is.

Could you please explain in layman's terms and in logical way.

The difference is in how method dispatch occurs. When you use new void Test1() , you're creating a new, identically named member that simply lexically shadows the original one: if you have a reference of type Class2 thing , an invocation of thing.Test1() is dispatched to the Class2.Test1 method, since it hides the original declaration.

If you assign the same object to a reference of type Class1 , the original declaration is no longer hidden, so invoking thing.Test1() on Class1 thing will result in Class1.Test1 being invoked.

When you use override , you are not hiding the original implementation; the original implementation is simply not available in the derived instance at all. You've swapped out the implementation of the original declaration, so regardless of whether you store the object in a reference of type Class1 or Class2 , invoking .Test1() will use the overriding implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM