1

I've got an issue with the non-allowed multiple inheritance in C#

Following scenario:

class MasterCamera { ... }

class CameraFromManufacturerA : MasterCamera { ... }

class CameraFromManufacturerB : MasterCamera { ... }

class CameraFromManufacturerC : MasterCamera { ... }

MasterCamera provides some functionality like StartCamera(), ConnectCamera(), etc. In my main code I use an object MasterCamera mCamera = CameraSelector.GetCamera(); with CameraSelector checking whether a camera from A, B or C is connected, and returns that object (e.g. CameraFromManufacturerA)

This works perfectly fine in theory, but one of these camera's API needs to use the WindowsMessageCallback (WndProc), thus I need to include for that camera only Windows.System.Forms.Form

Since C# does not allow multiple inheritance, and afaik Form has no interface class, I have to make MasterCamera inherit from Windows.System.Forms.Form

I do not want that, so how can I go around that?

4 Answers 4

2

You shouldn't use MasterCamera { ... } as a Class but use it as Interface like:

public interface MasterCamera { ... }

and it must work.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that worked. Didn't know you can use an interface as an object to call functions from.
This provides no means for implementing the common functionality.
That is true, but since every camera's manufacturers API is completely different, there is close to no common code at all.
2

This is a common problem with inheritance, which is why the GoF state "Favour composition over inheritance"

You could use the Strategy pattern. Instead of deriving different types of MasterCamera, instead derive different types of ICameraFunctionality, and store an object of that instance in your MasterCamera (or rather just Camera) class.

That way MasterCamera just does the common work, but calls its ICameraFunctionality instance to perform specific work.

Comments

1

What if you simply invert dependency in your code. Create a Form class that overrides WindowsMessageCallback and is able to host MasterCamera object, which would be that child Camera class that you need.

Comments

1

You are trying Inheritance. Give a try to Composition also.

Can't Camera be contained in a Form?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.