views:

148

answers:

4

I would like to achieve this in C#

(Pseudocode)

class A;

class B : A;

class C : A, B;

...

A ac = (A)c;

...

B bc = (B)c;

Is this possible?

+3  A: 

No. C# does not support multiple inheritance of classes.

A class may inherit from one class, and may also implement multiple interfaces.

John Saunders
Agreed. I'd like to hint at only one thing: Strictly speaking, a class does not _inherit_ interfaces, it _implements_ them.
stakx
@stakx: good catch. Corrected.
John Saunders
A: 

you can use Interfaces for multiple inheritance.

masoud ramezani
+2  A: 

It is not possible in C#, but, you should also think if this is the scenario you really want.

Is C really an A and a B ? Or does C has an A and a B. If the latter is true, you should use composition instead of inheritance.

Frederik Gheysels
I can't use composition for some reasons. Tried that. The problem: The base classes use delegates and providing references to itself in the callback. If C includes A and B the callbacks contain references to A and/or B, not to C as required. This is ensured if I inherit C from A and B.Interfaces are an option, use it already.
neil
+7  A: 

You do not need multiple inheritance in this particular case: If class C inherits only from B, any instance of class C can be cast to both B and A; since B already derives from A, C doesn't need to be derived from A again:

class A      { ... }

class B : A  { ... }

class C : B  { ... }

...

C c = new C();
B bc = (B)c;    // <-- will work just fine without multiple inheritance
A ac = (A)c;    // <-- ditto

(As others have already said, if you need something akin to multiple inheritance, use interfaces, since a class can implement as many of those as you want.)

stakx
Arggh... I've overseen the obvious. Thanks for the hint!Regards
neil
Hmmm. One problem remains: I can't force C to behave as A. B enhances A and doesn't provide plain A functionalities anymore (as required).Simply spoken I need a C, which sometimes behaves as A and sometimes as B, depending on the context.
neil
`C` should behave like `A` if you access it through `ac`; similarly, `C` should behave like `B` if you access it through `bc`. Of course, if you have virtual methods, the overridden versions will be called in all these cases.
stakx