[C#] Extend main interface on child level

Joined
Aug 31, 2023
Messages
1
Reaction score
0
Hi,

I am new to C# (coming from C++) and have a question concerning interfaces in a class hierarchy. I have the following structure:
  • main interface with only function declarations which every child has to implement
  • abstract base class derived from the interface with common function definitions (implementation is the same for all child classes)
  • child classes derived from the base class
The thing I am struggeling with is that some child classes also have functions which must be provided to the caller. These functions extend the main interface for the caller. I can think about different solutions but I dont know which one is good or bad design so I hope you can help me. Here are my approaches:

1. Derive child interface classes from base class. The caller has to know the 'Interface' and 'IChildx' datatypes and can cast the instance to the desired type.

diagram1.png


2. Derive the child classes from multiple interfaces. Here I do not derive an interface class from the base class. In C++ it has several disadvantages to derive an Interface from a class that contains code (definitions). I guess this is also the case in C#? Therefore I thought about this solution. The caller again has to cast the instance to the desired type.

diagram2.png


3. A different approach would be to implement the child interface functions in extra classes and add them as a member to the dedicated child. These new classes also must implement the System.Object interface. Then the user could get them by a function in the main interface and cast them with the 'as' operator.

diagram3.png


4. Last but not least: Add all functions, also those of the concrete child classes, to the main interface. Afterwards only one child class implements it and the other classes throw an exception. The disadvantage would be that the main interface gets extremely huge in the future.

It would be great if someone could tell me which solution is good and which is bad practice and explain why.

Greetings!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,818
Messages
2,569,727
Members
45,661
Latest member
NadineBour

Latest Threads

Top