1

While going through the differences between Abstract and virtual methods at Difference between Abstract and Virtual Function.

I got a doubt related to virtual and new

Let's consider a sample code as below

 class MainClass
 {
   public static void Main()
   {         
       DerivedClass _derived = new DerivedClass();          
       _derived.SayHello();          
       _derived.SayGoodbye();
       Console.ReadLine();
   }      
 }

public abstract class AbstractClass
{
   public void SayHello()
   {
       Console.WriteLine("Hello - abstract member\n");
   }

   public virtual void SayGoodbye()
   {
       Console.WriteLine("Goodbye- abstract member \n");
   }
   //public abstract void SayGoodbye();
}


public class DerivedClass : AbstractClass
{
   public new void SayHello()
   {
       Console.WriteLine("Hi There - Hiding base class member");
   }

   //public override void SayGoodbye()
   //{
   //    Console.WriteLine("See you later - In derived class OVERRIDE function");
   //}

   public new void SayGoodbye()
   {
       Console.WriteLine("See you later - In derived class I'm in  NEW  member");
   }           
}

My Question: In the derived class, How override and new perform the same functionality if i call SayGoodbye function? When i need to go to choose/ prefer among them? In which real time scenarios i need to prefer among them?

Community
  • 1
  • 1
venkat
  • 5,648
  • 16
  • 58
  • 83
  • 3
    http://stackoverflow.com/questions/392721/difference-between-shadowing-and-overriding-in-c – Oded Apr 19 '13 at 12:26
  • The question/answer @Oded links to perfectly answers your question. – David Hoerster Apr 19 '13 at 12:29
  • Just try this with your above code: `Console.WriteLine((AbstractClass)_derived.SayGoodbye());`. It will execute the base class method. That would not happen if you had overridden instead of hidden. – John Willemse Apr 19 '13 at 12:34

1 Answers1

2
  • When you mark a class member as virtual it can be overrided in the sub classes.
  • If you want to change a method (which was declared virtual in base class) in sub class you can use both new and override keywords but there is a difference between them

    . When using new: if you cast an object of sub class as base class, then call that method, base class implementation will run

    . When using override: if you cast an object of sub class as base class, then call that method, sub class implementation will run.

Here is the code

AbstractClass instance = new DerivedClass();
instance.SayGoodbye();  //See you later - In derived class I'm in  NEW  member

But if you use override

AbstractClass instance = new DerivedClass();
instance.SayGoodbye();  //Goodbye- abstract member \n
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116