66

A colleague and I are having a bit of an argument over multiple inheritance. I'm saying it's not supported and he's saying it is. So, I thought that I'd ask the brainy bunch on the net.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
  • 9
    **Interfaces alone are not a substitute for multiple inheritance**. This is because extending an established interface breaks all implementors. _huge_ issue. To (partially) work around this, code your methods & properties into a separate POCO object class, make an interface with just ONE property, of that class, that forces the implementor to expose all its functionality. Implementors/consumers of implementors will have to say this.ComposingOjbect.MIMethod() / implementor.ComposingOjbect.MIMethod() instead of this.MIMethod() / implementor.MIMethod() but it's worth it! – FastAl Jul 05 '12 at 14:07
  • 1
    @FastAl - "extending an established interface breaks all implementors" Why? I think that this is not true. – Nicolas Barbulesco Jan 02 '17 at 15:46
  • 4
    @NicolasBarbulesco - By Extending I mean actually adding a method. Then you get a compile-time error on the implementors until you write code in them to perform that function. Which is intended design; all I meant by 'break' is that multiple inheritance doesn't do that if you add a method to a base class, multiple inheritors needn't be touched. (I'm not making a statement on the wisdom of this practice - it's just an aspect of interfaces) – FastAl Jan 04 '17 at 20:21

17 Answers17

103

Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.

interface A { }
interface B { }
class Base { }
class AnotherClass { }

Possible ways to inherit:

class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)

This is not legal:

class SomeClass : Base, AnotherClass { }
Ry-
  • 218,210
  • 55
  • 464
  • 476
Asad
  • 21,468
  • 17
  • 69
  • 94
  • 5
    +1 for differentiating between implementation inheritance and interface inheritance – Gabe Moothart Mar 16 '10 at 16:42
  • 4
    +1 for nice clear code example. A picture speaks 1000 words, not sure how many a code example speaks... but it's good anyway. – Ian Mar 16 '10 at 16:57
46

Nope, use interfaces instead! ^.^

Barrie Reader
  • 10,647
  • 11
  • 71
  • 139
  • 9
    Surely as Senior .Net Developer you could tell him the answer :=P – Chris S Mar 16 '10 at 16:32
  • 5
    Note that you can write extension methods for interfaces, which can help to share implementation code. – TrueWill Mar 16 '10 at 17:06
  • 28
    -1 because: You cannot do "multiple inheritance" from interfaces, you can "implement" multiple interfaces - which IMHO is a completely different concept. The short answer to the question is till 3.5, you cannot do multiple inheritance in C# – Sunny Mar 16 '10 at 17:08
  • 18
    supporting interfaces is not the same thing as multiple inheritance. – D.C. Mar 16 '10 at 17:09
  • 1
    @Sunny: what changed in 3.5, in your opinion? – Konrad Rudolph Mar 16 '10 at 17:20
  • 1
    oops, I meant upto & including 3.5 you cannot do multiple inheritance in C#. I dont know if there is a way in 4.0 & beyond – Sunny Mar 16 '10 at 17:50
  • 9
    **Interfaces alone are not a substitute for multiple inheritance**, there are huge issues that will make your coding a nightmare, see my comment on the main answer. – FastAl Jul 05 '12 at 14:08
  • 1
    what do you do if the implementation of many methods is the same between all subclasses, how would you dry that up? – NullVoxPopuli May 05 '15 at 13:53
  • @Barrie Reader: Neither C# nor Java allow multiple inheritance, where multiple inheritance means to inherit from mutliple base classes assigned in one class. Python does allow a for multiple base classes. Interfaces are contracts and do not extend the class. You can however use a chain of inheritance where forexample, C extends B and B extends A. ...As per Asad Butt's answer. – James Sep 20 '16 at 13:02
  • @NullVoxPopuli You don't. My comment on the main answer helps a bit, but it's cumbersome. I call it 'interface composition' but like many patterns, it's a result of language deficiency. – FastAl Jan 04 '17 at 20:22
  • @James ... I would guess C# (and therefore .Net) never got multiple inheritance because Java didn't have it. (point of c# is compete with Java where VB6 had no chance ... multiple inheritance is powerful, but hard to implement, if you didn't foresee your competition adding it, why spend the effort?) – FastAl Jan 04 '17 at 20:24
  • The answer does say "nope" to answer the multiple-inheritance question, and suggests the use of interfaces as an alternative – James Hurley Jan 31 '17 at 22:13
  • 2
    Interfaces are not an alternative to inheritance. This is terribly misleading to someone new to C#. In trying to use them as an alternative, you'll do unnecessary duplicate work because every "child" class will have to newly implement the members of the "parent" interfaces anyway, so what have you gained? The answer by Liviu M is the closest thing to multiple inheritance, but is better because you keep your classes more loosely coupled than you would with multiple inheritance. – Chad Hedgcock Jun 04 '17 at 20:29
  • Interfaces are not a clean alternative to multiple inheritance. Interfaces have to be implemented, putting the same code in each class -- one of the key issues classes solves. This answer is misleading. – Xonatron Apr 14 '20 at 17:12
29

Multiple inheritance is not supported in C#.

But if you want to "inherit" behavior from two sources why not use the combination of:

  • Composition
  • Dependency Injection

There is a basic but important OOP principle that says: "Favor composition over inheritance".

You can create a class like this:

public class MySuperClass
{
    private IDependencyClass1 mDependency1;
    private IDependencyClass2 mDependency2;

    public MySuperClass(IDependencyClass1 dep1, IDependencyClass2 dep2)
    {
        mDependency1 = dep1;
        mDependency2 = dep2;
    }

    private void MySuperMethodThatDoesSomethingComplex()
    {
        string s = mDependency1.GetMessage();
        mDependency2.PrintMessage(s);
    }
}

As you can see the dependecies (actual implementations of the interfaces) are injected via the constructor. You class does not know how each class is implemented but it knows how to use them. Hence, a loose coupling between the classes involved here but the same power of usage.

Today's trends show that inheritance is kind of "out of fashion".

Kevin
  • 16,549
  • 8
  • 60
  • 74
Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65
  • 1
    Thank you for being the sole voice of reason, here. Anyone who has ever implemented OO in C, even at a basic level, understands that inheritance, under the hood, is nothing more than composition. So just compose your way around the supposed "problem"! – Engineer Sep 27 '16 at 20:44
  • 1
    The problem comes when the classes being composited have dozens of methods that you want to provide in the composite class. You are forced to write dozens of forwarding methods, instead of the alternative of allowing the inherited base class(es) to provide most of the (default) method implementations. – David R Tribble Dec 31 '16 at 17:46
  • 2
    This is THE right answer. The answers that say you can do it with interfaces do not understand interfaces. Interfaces are type constraints. They have nothing to do with inheritance. You still have to implement each member of an interface, so what are you inheriting? Also +1 for addressing--at least a little--why multiple inheritance is probably not what you want. – Chad Hedgcock Jun 04 '17 at 20:06
13

C# 3.5 or below does not support the multiple inheritance, but C# 4.0 could do this by using, as I remembered, Dynamics.

Gnought
  • 485
  • 5
  • 12
  • 3
    interesting feature... here is an article about just that http://www.codingday.com/multiple-inheritance-in-c-using-dynamic-features/ – tbischel Mar 16 '10 at 16:38
  • 2
    @tbischel Be sure to make note of the last comment on that article. The provided sample does not appear to work. – statenjason Mar 16 '10 at 16:47
  • 2
    While this **might** work, it's actually really ugly and requires a lot of reflection at runtime to get the job done. I would never allow such a solution in production code. – Scott Dorman Mar 16 '10 at 17:17
  • 1
    It wouldn't be *real* multiple inheritance. You can fake *some* aspects of MI using `dynamic`, I suspect - but it would have various bits of weird behaviour, I'm sure. – Jon Skeet Jul 24 '13 at 07:07
7

C# does not support multiple inheritance of classes, but you are permitted to inherit/implement any number of interfaces.

This is illegal (B, C, D & E are all classes)

class A : B, C, D, E
{
}

This is legal (IB, IC, ID & IE are all interfaces)

class A : IB, IC, ID, IE
{
}

This is legal (B is a class, IC, ID & IE are interfaces)

class A : B, IC, ID, IE
{
}

Composition over inheritance is a design pattern that seems to be favorable even in languages that support multiple inheritance.

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
7

You cannot do multiple inheritance in C# till 3.5. I dont know how it works out on 4.0 since I have not looked at it, but @tbischel has posted a link which I need to read.

C# allows you to do "multiple-implementations" via interfaces which is quite different to "multiple-inheritance"

So, you cannot do:

class A{}

class B{}

class C : A, B{}

But, you can do:

interface IA{}
interface IB{}

class C : IA, IB{}

HTH

Sunny
  • 6,286
  • 2
  • 25
  • 27
4

Like Java (which is what C# was indirectly derived from), C# does not support multiple inhertance.

Which is to say that class data (member variables and properties) can only be inherited from a single parent base class. Class behavior (member methods), on the other hand, can be inherited from multiple parent base interfaces.

Some experts, notably Bertrand Meyer (considered by some to be one of the fathers of object-oreiented programming), think that this disqualifies C# (and Java, and all the rest) from being a "true" object-oriented language.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52
  • 2
    I think Bertrand Meyer is a genius, but I would hardly call him one of the fathers of object-oriented programming. When he designed Eiffel in the 1980s, object-oriented programming was already 20 years old. It is true that some of the fathers of object-oriented programming do not consider C#, Java, C++ and co. to be object-oriented, but that doesn't have anything to do with the lack of multiple inheritance. (In fact, they don't consider inheritance to be essential at all, e.g. both Simula and Smalltalk-71 did not support inheritance.) It's the lack of message sending that bothers them. – Jörg W Mittag Mar 16 '10 at 16:55
  • 1
    Meyer defined seven criteria for "object-oriented", one of which is multiple inheritance. I'm not saying I agree with him, but he is not alone in this opinion. C++, it should be noted, has multiple inheritance. – David R Tribble Mar 16 '10 at 17:04
  • 4
    I also defined seven criteria for "object-oriented", one of which is being purple. However, since I didn't invent object-orientation, my criteria are utterly irrelevant and so are Meyer's. Alan Kay invented object-orientation (or more precisely, he invented the *word* "object-orientation"), so he and *only* he gets to decide what it means, and he has been very clear about it: "OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things" and "I made up the term object-oriented, and I can tell you I did not have C++ in mind." – Jörg W Mittag Mar 16 '10 at 18:11
  • 1
    C# doesn't support messaging. It does somewhat support information hiding, but it doesn't enforce it. And even with the `dynamic` features in C# 4.0, it only supports "*somewhat* late-binding of *some* things" and certainly not "*extreme* late-binding of *all* things." Please note that Alan Kay would be the first to readily admit that his *own* language, Smalltalk, doesn't exactly follow this ideal, either. Which is why he wanted to stop working on Smalltalk in 1975 or so, and develop a better language (and indeed, Smalltalk-76 and Smalltalk-80 were no longer designed by him). – Jörg W Mittag Mar 16 '10 at 18:18
  • In the system he is currently working on, for example, the language *syntax* is late-bound (like in Smalltalk-71, actually). The language *semantics* are late-bound. The type system is late-bound. Even the decision of whether or not to have a type system *at all* is late-bound. Heck, even the definition of what "late-bound" means is late-bound. – Jörg W Mittag Mar 16 '10 at 18:21
  • 7
    @Jörg: Saying that only one person gets to decide what is and what is not OO is absurd. The computer science scholar community at large ultimately decides what is OO, after much peer review and practical experience. That's the way it worked for structured programming, operating system theory, apect programming, patterns, etc. Meyer's opinions are held in higher regard than you indicate, BTW; see http://en.wikipedia.org/wiki/Object-Oriented_Software_Construction. – David R Tribble Mar 19 '10 at 17:26
4

Actually, it depends on your definition of inheritance:

  • you can inherit implementation (members, i.e. data and behavior) from a single class, but
  • you can inherit interfaces from multiple, well, interfaces.

This is not what is usually meant by the term "inheritance", but it is also not entirely unreasonable to define it this way.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
2

You may want to take your argument a step further and talk about design patterns - and you can find out why he'd want to bother trying to inherit from multiple classes in c# if he even could

Jason M
  • 512
  • 2
  • 8
2

In generally, you can’t do it.

Consider these interfaces and classes:

public class A { }    
public class B { }
public class C { }

public interface IA { }
public interface IB { }

You can inherit multiple interfaces:

class A : B, IA, IB {
  // Inherits any single base class, plus multiple interfaces.
}

But you can’t inherit multiple classes:

class A : B, C, IA, IB {
    // Inherits multiple base classes, plus multiple interfaces.
}
Evi1M4chine
  • 6,992
  • 1
  • 24
  • 18
Elshan
  • 7,339
  • 4
  • 71
  • 106
2

Multiple inheritance allows programmers to create classes that combine aspects of multiple classes and their corresponding hierarchies. For ex. the C++ allows you to inherit from more than one class

In C#, the classes are only allowed to inherit from a single parent class, which is called single inheritance. But you can use interfaces or a combination of one class and interface(s), where interface(s) should be followed by class name in the signature.

Ex:

Class FirstClass { }
Class SecondClass { }

interface X { }
interface Y { }

You can inherit like the following:

class NewClass : X, Y { } In the above code, the class "NewClass" is created from multiple interfaces.

class NewClass : FirstClass, X { } In the above code, the class "NewClass" is created from interface X and class "FirstClass".

2

You can't inherit multiple classes at a time. But there is an options to do that by the help of interface. See below code

interface IA
{
    void PrintIA();
}

class  A:IA
{
    public void PrintIA()
    {
        Console.WriteLine("PrintA method in Base Class A");
    }
}

interface IB
{
    void PrintIB();
}

class B : IB
{
    public void PrintIB()
    {
        Console.WriteLine("PrintB method in Base Class B");
    }
}

public class AB: IA, IB
{
    A a = new A();
    B b = new B();

    public void PrintIA()
    {
       a.PrintIA();
    }

    public void PrintIB()
    {
        b.PrintIB();
    }
}

you can call them as below

AB ab = new AB();
ab.PrintIA();
ab.PrintIB();
reza.cse08
  • 5,938
  • 48
  • 39
2

Simulated Multiple Inheritance Pattern
http://www.codeproject.com/KB/architecture/smip.aspx enter image description here

Donny V.
  • 22,248
  • 13
  • 65
  • 79
1

It does not allow it, use interface to achieve it.

Why it is so?

Here is the answer: It's allowed the compiler to make a very reasoned and rational decision that was always going to consistent about what was inherited and where it was inherited from so that when you did casting and you always know exactly which implementation you were dealing with.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
Awais Ahmad
  • 89
  • 1
  • 11
  • C++ solved it no problem, and VB.net even provides a syntax for the diamond problem with interfaces: `function MyMethod_1() as string implements i1.MyMethod` and `function MyMethod_2() as string implements i2.MyMethod` note the naming of MyMethod. Then consumers can cast to i1 or i2 if they only know the base type, to get the right MyMethod, or, call MyMethod_1 or MyMethod_2 for the concrete type. – FastAl Jan 04 '17 at 20:27
  • Interfaces achieve a completely different objective than base classes with multiple inheritance. A class is an implementation of an interface. An interface does not contain actual runnable code -- only an expected prototype/declaration. – JamesHoux Aug 03 '18 at 19:16
1

C# does not support multiple inheritance built in.

For adding multiple inheritance to languages that does not support it, You can use twin design pattern

Nik Kashi
  • 4,447
  • 3
  • 40
  • 63
0

As an additional suggestion to what has been suggested, another clever way to provide functionality similar to multiple inheritance is implement multiple interfaces BUT then to provide extension methods on these interfaces. This is called mixins. It's not a real solution but it sometimes handles the issues that would prompt you to want to perform multiple inheritance.

Jaxidian
  • 13,081
  • 8
  • 83
  • 125
  • 1
    Strictly speaking, .NET does not provide support for true mixins. Instead, it provides extension methods which serve some of the same uses and give some of the same benefits as mixins. – Scott Dorman Mar 16 '10 at 17:19
  • Agreed. This is a partial mixin implementation in the technical sense. However, I've heard quite a few people still refer to this as ".NET Mixins". But you are correct. – Jaxidian Mar 16 '10 at 17:33
  • 1
    Mixins are kind of a dual to interfaces: with classes, you inherit both implementation and interface, with interfaces you inherit only interface and no implementation, with mixins you inherit only implementation and no interface. Note that mixins serve a different purpose, though: mixins are used to *compose* classes (or objects in a classless language), so they are a *smaller* unit of the system than a class/interface/object. One class/object is made up of several mixins. – Jörg W Mittag Mar 16 '10 at 18:25
0

I recently somehow got to the same mindset, inheriting two classes into a class and ended up on this page (even though i know better) and would like to keep reference to the solution i found perfect in this scenario, without enforcing implementation of interfaces

My solution to this problem would be splitting up your data into classes that make sense:

public class PersonAddressSuper
{
    public PersonBase Person { get; set; }
    public PersonAddress Address { get; set; }

    public class PersonBase
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    public class PersonAddress
    {
        public string StreetAddress { get; set; }
        public string City { get; set; }
    }
}

Later on in your code, you could use it like this:

Include Both Parts, Base & Address

PersonAddressSuper PersonSuper = new PersonAddressSuper();
PersonSuper.PersonAddress.StreetAddress = "PigBenis Road 16";

Base Only:

PersonAddressSuper.PersonBase PersonBase = new PersonAddressSuper.PersonBase();
PersonBase.Name = "Joe Shmoe";

Address Only:

PersonAddressSuper.PersonAddress PersonAddress = new PersonAddressSuper.PersonAddress();
PersonAddress.StreetAddress = "PigBenis Road 16";
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93