Use Of virtual new in C#

Sabarimahesh
Posted by Sabarimahesh under C# category on | Points: 40 | Views : 1437
We Have 5 Classes: One Baseclass and Four DerivedClasses


The BaseClass have a Virtual method

The First Derived class Have a method with "new" Key word ,

i.e;Data of this class will be hidden.

This is the Major purpose Of Using New Keyword.

We Override All The other Derived classes except the First Derived class.

Note: 
You Can't Use This:
public new void Show()
DerivedClass2.Show() cannot override inherited member DerivedClass.Show() because it is not marked virtual, abstract, or override

You Can Use this
public virtual new void Show()
Because this is also a Virtual Method



Snippet:
class Program
{
static void Main(string[] args)
{
Baseclass bc;
bc = new DerivedClass2();
bc.Show();
bc = new DerivedClass4();
bc.Show();
Console.ReadLine();

}

}

class Baseclass
{
public virtual void Show()
{
System.Console.WriteLine("Baseclass::Show");
}
}

class DerivedClass : Baseclass
{
public virtual new void Show()
{
System.Console.WriteLine("DerivedClass::Show");
}
}
class DerivedClass2 : DerivedClass
{
public override void Show()
{
System.Console.WriteLine("DerivedClass2::Show");
}
}
class DerivedClass3 : DerivedClass2
{
public override void Show()
{
System.Console.WriteLine("DerivedClass3::Show");
}
}
class DerivedClass4 : DerivedClass3
{
public override void Show()
{
System.Console.WriteLine("DerivedClass4::Show");
}
}



OutPut 
Baseclass::Show
Baseclass::Show

Comments or Responses

Login to post response