What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 21497 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > C# > Use Of virtual new in C# ...
Sabarimahesh

Use Of virtual new in C#

 Code Snippet posted by: Sabarimahesh | Posted on: 5/8/2012 | Category: C# Codes | Views: 589 | Status: [Member] | Points: 40 | Alert Moderator   


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


Life is a Race
Thanks & Regards
By
Sabari Mahesh P M
Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/22/2013 7:12:00 AM