Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » C# Language » Multiple Inheritance in C#

Multiple Inheritance in C#

Can you inherit from multiple classes in C#? Simply put, this cannot be done. However there are ways around it. From a design perspective you must ask yourself, will a Class fully represent an object?

Total page views :  121143
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Download Free Book

Can you inherit from multiple classes in C#? Simply put, this cannot be done. However there are ways around it. From a design perspective you must ask yourself, Will a Class fully represent an object? Meaning that, if we have a base class with abstract methods designed for a particular application and we know that the inheriting object will only need the methods defined in that class. We now have a valid design pattern here.

The Vehicle Car Object

Lets say we have an abstract class called "Vehicle" as well as another class called "ConstructionVehicle". The vehicle class has methods such as Accelerate() , Stop(), and the "ConstructionVehicle" class has methods such as ExecuteDump() and TurnOnBackUpSound(). If we were only going to build a Car object and know we would only use those methods from the "Automobile" class this would be fine.

The DumpTruck Object

Now we want to create another object called "DumpTruck". We could inherit from the Automobile class but that class does not have the methods that we need called ExecuteDump() and TurnOnBackUpSound(). If we were using a language such as C++ we could easily inherit from both classes using multiple inheritance. However, seeing C# is our language of choice, multiple inheritance is not an option, you may only inherit from one Base Class.

From Abstract Classes to Interfaces

From a design perspective we must choose a different design. C# supports what is called "Multiple Implementation", which is to says a class can implement more than one interface. Our design now changes the "Vehicle" class and the "ConstructionVehicle" class into interfaces. Below we have defined the two interfaces with their very simplistic methods. i.e :

interface IConstructionVehicle
{
void ExecuteDump();
void TurnOnBackUpSound();
}
interface IVehicle
{
void Accelerate();
void Stop();
void TurnOnBackUpSound();
}

If we built a class that inherited from these two interfaces we would be able to do so spanning multiple inherited interfaces. Design problem solved!

Or is it?

Explicit Interface Implementation

If you look at both interfaces defined above you'll notice that they share in common a method of the same name "TurnOnBackUpSound()". Problem? No, in fact C# supports what is known as "Explicit Interface Implementation", which allows the programmer to specify which member of which interface they want to use. Putting the Interface name in front of the member name allows this to happen as shown below.

public class DumpTruck: IEngine, IBody
{
void IEngine.Test()
{
Console.WriteLine("This is the Engine TEst");
}
void IBody.Test()
{
Console.WriteLine("This is the Body TEst");
}
}

Implementation Hiding

Another benefit to this technique is something called "Implementation Hiding". Implementation Hiding allows the methods from the implemented interface to be hidden from the derived class unless the developer explicitly calls the interface. This technique obviously reduces the clutter for a developer.


Login to add your contents and source code to this article
 About the author
 
Craig Breakspear
Craig Breakspear MIT, MCSD
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments
Not at all impressive by surendra On August 23, 2007
Not at all impressive
Reply | Email | Delete | Modify | 
it is over by Sujit On February 27, 2008
interface is a vast topic.this car and vehicle is not sufficient. these article should not be posted like this.
Reply | Email | Delete | Modify | 
Multiple Inheritance by Hari On October 17, 2008
why multiple inheritance is not good in programming?
Reply | Email | Delete | Modify | 
Incomplete example by Jonathan On November 6, 2008
Suppose you also have ISportUtilityVehicle and IRover whose 'Accelerate' methods are no different than that of the base class. Then, the best you can do is put the common functionality in a static method and call it from all three implementations of 'Accelerate' (with one line wrappers). Isn't this the real PITA about single inheritance languages? I would be interested to see you actually address this elephant in the room.
Reply | Email | Delete | Modify | 
So bad by Phan On January 18, 2009
Not new anything
Reply | Email | Delete | Modify | 
To everyone that submitted a comment... by John On June 26, 2009
This article is from 2001 when C# was a "newer" language. Posting in 2007-2009 saying your not impressed by this article makes me sad to program in C#. Because you cannot read a date, and just learned "Hello World" in VB doesn't mean you should search the web at night looking for foundation articles from 2001 and cry on them.

Good thing none of you will ever program professionally... At least that is a relief.

Reply | Email | Delete | Modify | 
Using method definitions by Dulantha On August 4, 2009
So what if I want to use the method definitions as well - not just the method signatures?
Reply | Email | Delete | Modify | 
Thanks Craig. Nice short summary by Joe On November 17, 2009

It is disconcerting that so many people had negative responses to this article. 

 

The article was concise, to the point and covered at least a couple design issues (which is plenty for any article).  Those who desire a thesis should spend their time searching for one, not insulting “quick summary” authors.  As to “date of the article”, who cares?  As to the obvious bash about professional programmers.  I am one who wrote a flight simulator with shading before any were commercially available and a logistics algorithm attempted by 17 others before me (includes 6 PhD’s) that saves our nation an estimated 1.2 million per hour.

 

I think this was great and thank you very much sir!

 

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved