Is it possible to extend 2 classes at once?

It is not possible to inherit multiple base classes in C#. You are able to implement two interfaces, or follow some workarounds (though this should be done with caution).

Links:

  • SO: Multiple Inheritence in C#: Discussion of MI methods and a good description of "composition".
  • Code Project: An example of a workaround
  • C-SharpCorner: Some alternatives to multiple inheritence

In the case where you need to extend two classes, you might be served to favor composition over inheritance, and to use interfaces as other answers have mentioned. An example:

Start by definining your interfaces

interface IFoo 
{
    void A(); 
}

interface IBar
{
    void B();
}

Then create concrete classes that implement each interface

class Foo : IFoo
{
    public void A()
    {
         // code
    }
}

class Bar : IBar 
{
    public void B()
    {
         // code 
    }
}

Finally, in the class you want to exhibit both sets of behaviors, you can implement each interface but compose the implementations with the concrete classes.

public class Baz : IFoo, IBar
{
    IFoo foo = new Foo(); // or inject 
    IBar bar = new Bar(); // or inject

    public void A()
    {
        foo.A();
    }

    public void B()
    {
        bar.B();
    }
}

This is called Multiple Inheritance. You can find more information on Wikipedia - Multiple inheritance regarding the subject.

Multiple inheritance is supported in some langages:

Languages that support multiple inheritance include: C++, Common Lisp, Curl, Dylan, Eiffel, Logtalk, Object REXX, Scala, OCaml, Perl, Perl 6, POP-11, Python, and Tcl

In C#, interfaces can be used for mimicking multiple inheritance:

Some object-oriented languages, such as C#, Java, and Ruby implement single inheritance, although interfaces provide some of the functionality of true multiple inheritance.

Example:

public class myClassData : myClassPageInterface, myClassControlInterface 
{
    // ...
}

Tags:

C#

.Net