Hi,
I am new to C# (coming from C++) and have a question concerning interfaces in a class hierarchy. I have the following structure:
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.
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.
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.
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!
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
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.
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.
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.
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!