0

Please find the code below:

using System;

namespace MainNS
{
    abstract class BaseClass
    {
        abstract public void fun();
     }

    class DerivedClass1 : BaseClass
    {
        override public void fun()
        {
            Console.WriteLine("fun() of DerivedClass1 invoked!");
        }

    }

    class DerivedClass2 : DerivedClass1
    {
        new public void fun()
        {
            Console.WriteLine("fun() of DerivedClass2 invoked!");
        }

    }

    class MainClass
    {

        public static void Main(string[] args)
        {
            DerivedClass1 d1 = new DerivedClass2();
            d1.fun();
            Console.ReadKey();
        }
    }

}

What is the use of replacing new with override here and Please explain the actual concept behind this.

Override keyword makes fun() of DerivedClass2 to be executed and new keyword makes fun() of DerivedClass1 to be executed.

 class DerivedClass2 : DerivedClass1
   {
        new public void fun()
        {
            Console.WriteLine("fun() of DerivedClass2 invoked!");
        }
    }
pravprab
  • 2,301
  • 3
  • 26
  • 43
Sathish
  • 55
  • 1
  • 3

1 Answers1

0

The following page summarizes your question very nicely.

Knowing When to Use Override and New Keywords

Summary

Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.

New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.

If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).

Override: used with virtual/abstract/override type of method in base class

New: when base class has not declared method as virtual/abstract/override

New Vs Override

Community
  • 1
  • 1
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
  • Does fun() of DerivedClass1 act as a virtual/abstract method because it is overriden by fun() of DerivedClass2. No keyword (virtual/abstract) was mentioned in DerivedClass1 btw. – Sathish Feb 05 '14 at 10:14