Pages

Wednesday 26 February 2014

Difference between Virtual Override New Keywords with Example c#

Difference between Virtual Override New Keywords with Example c#

Generally virtual and override keywords will occur in overriding method of polymorphism concept and new keyword will be used to hide the method. Here I will explain these keywords with example for that check below code. I have one method Show() which exists in two classes SampleA and SampleB as shown below

 using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public void Show()
{
Console.WriteLine("Sample B Test Method");
}
}

class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}

Output:

Sample A Test Method
Sample B Test Method
Sample A Test Method

New Keyword Example or Method Hiding

 using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}

Virtual and Override Keywords Example or Method Overriding:


using System;
namespace ConsoleApplication3
{
class SampleA
{
public virtual void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public override void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}

Output:

Sample A Test Method
Sample B Test Method
Sample B Test Method

Use Both Method Overriding & Method Hiding:

 using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new virtual void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class SampleC : SampleB
{
public override void Show()
{
Console.WriteLine("Sample C Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
SampleB c = new SampleC();
a.Show();
b.Show();
c.Show();
a = new SampleB();
a.Show();
b = new SampleC();
b.Show();
Console.ReadLine();
}
}
}

Output:

Sample A Test Method
Sample B Test Method
Sample C Test Method
Sample A Test Method
Sample C Test Method



No comments:

Post a Comment