Overview of inheritance with C# : part 1

When base class and derived class both have same method but base class's method is not virtual, and derived class's method is not overridden, then if we instantiate the object of base class to derived class and call the method with respect to the object created, the method written in base class will be invoked.

Sample code

namespace Inheritance { class Program { static void Main(string[] args) { BaseDemo bd = new DerivedDemo(); bd.PrintString(); Console.ReadLine(); } } class BaseDemo { public BaseDemo() { } public void PrintString() { Console.WriteLine("Base Demo Invoked"); } } class DerivedDemo : BaseDemo { public DerivedDemo() { } public void PrintString() { Console.WriteLine("Derived Demo Invoked"); } } }
Output
Base Demo Invoked

Compilation of above code will generate warning that
"Warning 1 'Inheritance.DerivedDemo.PrintString()' hides inherited member Inheritance.BaseDemo.PrintString()'. Use the new keyword if hiding was intended."

new keyword

To remove the above warning or to hide the base method and give new definition of the method in derived class we must use new keyword for declaring the method in the derived class. The new keyword will hide the base method and create new method definition in derived class.

Sample Code

namespace Inheritance { class Program { static void Main(string[] args) { BaseDemo bd = new DerivedDemo(); bd.PrintString(); Console.ReadLine(); } } class BaseDemo { public BaseDemo() { } public void PrintString() { Console.WriteLine("Base Demo Invoked"); } } class DerivedDemo : BaseDemo { public DerivedDemo() { } public new void PrintString() { Console.WriteLine("Derived Demo Invoked"); } } }
Output
Base Demo Invoked

No comments:

Post a Comment