dannyyy
dannyyy

Reputation: 1784

Base / Derived Type Generics Parameter

I'd like to have an abstract method inside an abstract class and method signature like this:

public abstract IEnumerable<SynchronizeItem<IDataItem>> Sync(IEnumerable<SynchronizeItem<IDataItem>> clientSyncItems);

In the derived class I want to define the method type safety:

public override IEnumerable<SynchronizeItem<AdItem>> Sync(IEnumerable<SynchronizeItem<AdItem>> clientSyncItems)
{
    // Do something with the AdItems
    _adHandler.Foo(clientItems):
}

This is not possible. Any other possibilities to achieve the same behavior? I don't want to cast each usage of IDataItem to it's specific implementation within AdHandler class.

Upvotes: 1

Views: 86

Answers (2)

Kirk Woll
Kirk Woll

Reputation: 77546

Renen's answer will not do quite what you want, as it appears to me you want the subclass to define the concrete type, not the caller. To do this, make the type argument a part of the base class, not the method:

public class Base<T> where T : IDataItem
{
    public abstract IEnumerable<SynchronizeItem<T>> Sync(
        IEnumerable<SynchronizeItem<IDataItem>> 
        clientSyncItems);
}

And your derived class:

public class Derived : Base<AdItem>
{
    public override IEnumerable<SynchronizeItem<AdItem>> Sync(
        IEnumerable<SynchronizeItem<AdItem>> 
        clientSyncItems) 
    { ... }
}

Upvotes: 1

RMalke
RMalke

Reputation: 4094

Try to define your abstract method like:

public  IEnumerable<SynchronizeItem<T>> Sync<T>(IEnumerable<SynchronizeItem<T>> clientSyncItems)  where T : IDataItem;

Your other method, the implementation, is correct.

Upvotes: 2

Related Questions