Can you satisfy an interface with an IEnumerable<T> by using List<T>?

Let's say I have the following Model:

public interface IProduct
{
    IEnumerable<Ingredient> Ingredients { get; set; }
}

public class Product : IProduct
{
    public IEnumerable<Ingredient> Ingredients { get; set; }
}

public class Ingredient
{
}

But I want Ingredients to be a List<Ingredient> instead of an IEnumerable<Ingredient>

Is there a way to model the interface to accept IEnumerable<T> and List<T>?

I tried the following. But of course, the syntax doesn't support this and doesn't see TEnumerable<Ingredient> as a generic parameter.

public interface IProduct<TEnumerable<Ingredient>> 
    where TEnumerable<Ingredient> : IEnumerable<Ingredient>
{
    TEnumerable<Ingredient> Ingredients { get; set; }
}

public class Product : IProduct
{
    public List<Ingredient> Ingredients { get; set; }
}

public class Ingredient
{
}

I realize this isn't very practical, but I am just looking at this with curiosity in mind.

Jon Skeet
people
quotationmark

Your syntax is a bit off:

  • You can't declare a type parameter in a generic way like this
  • Your Product type needs to specify a type argument when it says how it's implementing IProduct<TEnumerable>

So this is valid:

public interface IProduct<TEnumerable> 
    where TEnumerable : IEnumerable<Ingredient>
{
    TEnumerable Ingredients { get; set; }
}

public class Product : IProduct<List<Ingredient>>
{
    public List<Ingredient> Ingredients { get; set; }
}

It may not be helpful, but at least it's valid...

people

See more on this question at Stackoverflow