21

I have these classes :

public class myClassPage : System.Web.UI.Page
{
    public myClassPage ()
    {
    
    }
}

public class myClassControl : System.Web.UI.UserControl
{
    public myClassControl ()
    {
    
    }
}

and I'd like have another Class that extends these classes, something like this :

public class myClassData : myClassPage, myClassControl
{
    public myClassData ()
    {
    
    }
}

is it possible to do this or is there something else I could do?

riQQ
  • 9,878
  • 7
  • 49
  • 66
markzzz
  • 47,390
  • 120
  • 299
  • 507

5 Answers5

29

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();
    }
}
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
16

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 
{
    // ...
}
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • Example: `public class myClassData : myClassPageInterface, myClassControlInterface { ... }` – Heinzi Jul 12 '11 at 13:52
5

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:

Community
  • 1
  • 1
user664939
  • 1,977
  • 2
  • 20
  • 35
3

use interface

in c# class Multiple inheritance not support

also refer

http://en.wikipedia.org/wiki/Multiple_inheritance

Dinesh Rabara
  • 1,119
  • 12
  • 13
3

It is not possible, but look at this link.

Simulated Multiple Inheritance Pattern

Orhan Cinar
  • 8,403
  • 2
  • 34
  • 48