user1038502 user1038502 - 3 months ago 30
C# Question

Best practise for implementing multiple interfaces in C#

I am working within a framework where you do the following:

IMyClass instance = Session.GetAllObjectsOfType("IMyClass")[0];
ILock lock = instance as ILock;
if(lock != null)

ISaveable saveable = instance as ISaveable;
if(saveable != null);

For this to work I have

class MyClass : IMyClass, ISaveable, ILock


I reality I have something like 8-15 interfaces I need to implement and they need to be accessable by casting the main object. What is the cleanest way to implement this? I looked into the facade patter, but I dont think that can be used here.


Based on your comment:

I was hoping there was a better way then the obvious one. There will be a lot of code going into the realisation the the different interfaces, and the ILock interface does not really need to know about the ISavebale functionalty. I am basically looking for a clean way to do this that does not result in one class with 5k lines of code and 200 public functions

If you want a class to implement the interface the class will need to inherit the interface but the functionality could be injected and wrapped (aka Facade).

This would be the cleanest way to achieve your goal of generic but separate code classes for ISaveable, ILock etc.

For example:

public MyClass : IMyClass, ISaveable, ILock
    private readonly ISaveable _saveableImplementation;
    private readonly ILock _lockImplementation;

    public MyClass(ISaveable saveableImplementation, ILock lockImplementation)
        _saveableImplementation = saveableImplementation;
        _lockImplementation - lockImplementation;

    public void ISaveable.Save()

    public void ILock.Lock()