jaybny
jaybny

Reputation: 1028

Need multiple inheritance functionality in C#. What am I doing wrong?

class UDPClient
{
}

class LargeSimulator
{
}

class RemoteLargeSimulatorClient : UDPClient, LargeSimulator
{
}

The saying goes, if you need multiple inheritance, your design is off.

How would I get this done in C# without having to implement anything?

Upvotes: 4

Views: 5927

Answers (6)

daveaglick
daveaglick

Reputation: 3678

One possible substitute for multiple inheritance is mixins. Unfortunately C# doesn't have those either, but workarounds are possible. Most rely on the use of extension methods (as a previous answerer suggested). See the following links:

http://mortslikeus.blogspot.com/2008/01/emulating-mixins-with-c.html http://www.zorched.net/2008/01/03/implementing-mixins-with-c-extension-methods/ http://colinmackay.co.uk/blog/2008/02/24/mixins-in-c-30/

Upvotes: 1

Marino Šimić
Marino Šimić

Reputation: 7342

interface ILARGESimulator
{
}

interface IUDPClient
{
}

class UDPClient : IUDPClient
{
}

class LargeSimulator : ILARGESimulator
{
}

class RemoteLargeSimulatorClient : IUDPClient, ILargeSimulator
{
    private IUDPClient client = new UDPClient();
    private ILARGESimulator simulator = new LARGESimulator();

}

Unfortunately you will need to write wrapper methods to the members. Multiple inheritance in C# does not exist. You can however implement multiple interfaces.

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23132

The short answer: Multiple inheritance is not allowed in C#. Read up on interfaces: http://msdn.microsoft.com/en-us/library/ms173156.aspx

The slightly longer answer: Maybe some other design pattern would suit you, like the strategy pattern, etc. Inheritance isn't the only way to achieve code reuse.

Upvotes: 0

Brandon Moretz
Brandon Moretz

Reputation: 7621

You can only inherent from a single base class in C#. However, you can implement as many Interfaces as you'd like. Combine this fact with the advent of Extension Methods and you have a (hacky) work-around.

Upvotes: 5

Tony The Lion
Tony The Lion

Reputation: 63190

To get multiple inheritance the way you want it, you need to make your UDPClient and LargeSimulator interface instead of class.

Class multiple inheritance isn't possible in C#

Upvotes: 1

Neil N
Neil N

Reputation: 25258

C# only allows single inheritance, though you can inherit from as many interfaces as you wish.

You could pick just one class to inherit from, and make the rest interfaces, or just make them all interfaces.

You could also chain your inheritence like so:

class UDPClient
{
}

class LargeSimulator : UDPClient
{
}

class RemoteLargeSimulatorClient : LargeSimulator
{
}

Upvotes: 5

Related Questions