Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
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?

Page Views : 235005
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
Mindcracker MVP Summit 2012
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate 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.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Not at all impressive by surendra On August 23, 2007
Not at all impressive
Reply | Email | 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 | Modify 
Multiple Inheritance by Hari On October 17, 2008
why multiple inheritance is not good in programming?
Reply | Email | 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 | Modify 
So bad by Phan On January 18, 2009
Not new anything
Reply | Email | 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 | 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 | 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 | Modify 
Example by Kenneth On February 19, 2010
I think your explanation is very good, but the example is not correct.
In this case you should just inherit ConstructionVehicle from Vehicle and make an inheritance hierarchy.

A better example would be a class like a button.
It can be pushed, or it can be dragged, so it would implement the interfaces IPushable and IDraggable. Other items (such as a Label), can only be dragged and would only implement IDraggable.

Good explanation though

With kind regards,

Kenneth Truyers

Host Ahead
Reply | Email | Modify 
question about multipleinheritance by madhavarao On March 26, 2010
how to achieve multiple inhertance,which method will execiute first and how ?
by observing this code and send clear explanation without creating reference variable to the interfaces in c#.net
1. Interface Inter1
{
void Test();
}
2.Interface Inter2
{
 void Test();
}
Reply | Email | Modify 
Good job, to the point by Oz On September 14, 2010
I think the article did exactly what it was suppossed to do, educate those that do NOT know enough about the subject and need help. Thank you so much, it did help.

To the complainers:  Stop being so errogant. Just because you see no value does not mean no value exists. You will never fly high with the eagles if you continue to behave like crow.
Reply | Email | Modify 
regarding clarification by SYED On March 8, 2011
i have class a { } class b:a { } class c:a { } can this be done...please reply soon thanks in advance...interview question
Reply | Email | Modify 
Not at all good by Chetna On May 25, 2011
Poor.Not Clear.
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.