Him
Him

Reputation: 373

Implement an interface method with a concrete class

I have the following interfaces, one for the entity and one for some logic:

public interface IItem 
{ 
    int Id { get; set; }
}

public interface IGenerator
{
    IList<IItem> Generate();
}

and implementation:

public class ItemA : IItem 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ItemAGenerator : IGenerator
{
    public IList<ItemA> Generate()
    {
        // do stuff
        return List<ItemA>;
    }
}

That implementation did not work, it says that it does not have the matching return type, so I also tried:

public class ItemAGenerator : IGenerator
{
    public IList<IItem> Generate()
    {
        // do stuff
        return List<ItemA>;
    }
}

it does not work as well, it says: cannot implicitly convert type List<IItem> to List<ItemA>.

How to make it work? what am I missing here.

Upvotes: 1

Views: 2187

Answers (2)

juharr
juharr

Reputation: 32266

Just make IGenerator generic. Then you can specify the type that will be returned.

public interface IGenerator<T> where T : IItem
{
    IList<T> Generate();
}

public class ItemAGenerator : IGenerator<ItemA>
{
    public IList<ItemA> Generate()
    {
        // do stuff
        return List<ItemA>;
    }
}

Upvotes: 1

Paul
Paul

Reputation: 3306

Just create the list as a List<IItem> but add ItemA's to it.

public class ItemAGenerator : IGenerator
{
    public IList<IItem> Generate()
    {
        var list = new List<IItem>();
        list.Add(new ItemA());

        return list;
    }
}

Upvotes: 2

Related Questions