Virtual, Override and new Keyword in C#

Virtual, Override and new Keyword in C#

Consider following class Hierarchy:

Multilevel Inheritance

In this example, we will consider three classes which are TestA, TestB and TestC.

namespace OOPS_Concept

{

class TestA

{

public void display() { Console.WriteLine("TestA – display()"); }

}

class TestB : TestA

{

public void display() { Console.WriteLine("TestB – display()"); }

}

class Test

{

static void Main(string[] args)

{

TestA a;

TestB b;

a = new TestA();

b = new TestB();

a.display(); // TestA – display()

b.display(); // TestB – display()

a = new TestB();

a.display(); // TestA – display()

Console.Read();

}

}

}

output :

TestA – display()
TestB – display()
TestA – display()

Program will compile and run successfully but

  • The Problem of above code is that, third output should be “TestB –display()” because the variable a have the object of B.
  • …Test.cs(15,21): warning CS0108: ‘OOPS_Concept.TestB.display()’ hides inherited member ‘OOPS_Concept.TestA.display()’. Use the new keyword if hiding was intended.

Lets resolve the problem 1.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s