Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic abstract base class from Generic Interface

I'm trying to understand what hierarchy would be the best for inheritance described as following. So far I have had as following:

public interface IManager<T> where T : ISomeObject
{
    bool Add(T o);
    bool Remove(T o);
    bool Update(T o);
}

But then I wanted each derived classes to have a parameterised constructor. So I went:

public abstract class Manager<T> : IManager<T> where T : ISomeObject
{
    protected readonly INeededObject obj;

    protected Manager(INeededObject o)
    {
         obj = o;
    }
}

Any ideas on how should I go about this design issue? Thanks in advance.

like image 525
Kunal Avatar asked Dec 30 '25 13:12

Kunal


2 Answers

You're almost there. You can use generic type parameters in your base class as well.

public abstract class Manager<T> : IManager<T> where T : ISomeObject
{
    protected readonly T obj;

    protected Manager(T o)
    {
         obj = o;
    }
}

You can use parameterized types too, like

protected Manager(IList<T> o)
{
    ...
}
like image 91
p.s.w.g Avatar answered Jan 02 '26 03:01

p.s.w.g


May be a bit of late night 'wisdom rush' (which can be wrong again). But modified my interface to be a non-generic one as followed:

public interface IManager
{
    bool Add(ISomeObject o);
    bool Remove(ISomeObject o);
    bool Update(ISomeObject o);
}

And my abstract class looks like following:

public abstract class Manager<T> : IManager<T> where T : ISomeObject
{
    protected readonly INeededObject obj;

    protected Manager(INeededObject o)
    {
         obj = o;
    }

    public abstract bool Add(T o);
    bool IManager.Add(ISomeObject obj)
    {
        return this.Add( (T) obj );
    }
}
like image 23
Kunal Avatar answered Jan 02 '26 01:01

Kunal



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!