Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about C# inheritance with similar interfaces

Tags:

c#

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.

like image 617
Elliott Avatar asked Oct 25 '25 11:10

Elliott


1 Answers

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;
    }
}
like image 70
Metro Smurf Avatar answered Oct 28 '25 02:10

Metro Smurf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!