Home > Mobile >  Question about C# inheritance with similar interfaces
Question about C# inheritance with similar interfaces

Time:08-10

I was recently working on a project where I needed to have the following functionality:

public interface IStart
{
    public void StartStarting();
    public bool IsDoneStarting();
}

public interface IEnd
{
    public void StartEnding();
    public bool IsDoneEnding();
}

These two interfaces basically do the same thing:

public interface IDo
{
    public void StartDoing();
    public bool IsDoneDoing();
}

Is there somehow a way to inherit IDo twice rather than IStart and IEnd individually? I highly doubt it, but it would certainly be convenient.

CodePudding user response:

Another option to consider is using composition over inheritance. In a composition scenario, the IStart and IEnd implementations would be passed in to the .ctor, then accessed as properties.

Code is worth a thousand words...

public interface IDo
{
    void StartDoing();
    bool IsDoneDoing();
}

public interface IStart : IDo { }
public interface IEnd : IDo { }

public interface IWorker
{
    IStart Start { get; }
    IEnd End { get; }
}

public class Worker : IWorker
{
    public IStart Start { get; }
    public IEnd End { get; }

    public Worker( IStart start, IEnd end )
    {
        Start = start;
        End = end;
    }
}

CodePudding user response:

It can't be done to inherit one interface to the next. If you want a commonality expressed as such, I suggest using an abstract class which pulls in both interfaces and expresses that syntactic sugar you seek as such:

public abstract class IDo :  IStart, IEnd
{
    public void StartDoing() { StartStarting(); }
    public bool IsDoneDoing() { return IsDoneEnding() }


    public virtual void StartStarting() {}
    public virtual bool IsDoneStarting() { return false; } // Override me.

    public virtual void StartEnding()  { }
    public virtual bool IsDoneEnding() { return false; } // Override me.

}
  •  Tags:  
  • c#
  • Related