Why use IEnumerable <T> in an interface definition if the class implementing the interface uses List <T>?
I am currently working on a .NET Web API tutorial located here . In the example, we have an interface defined in the model class, for example:
namespace ProductStore.Models
{
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product Get(int id);
Product Add(Product item);
void Remove(int id);
bool Update(Product item);
}
}
Then, later in the tutorial, we implement this interface as follows:
namespace ProductStore.Models
{
public class ProductRepository : IProductRepository
{
private List<Product> products = new List<Product>();
private int _nextId = 1;
public ProductRepository()
{
Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M });
Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M });
Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M });
}
public IEnumerable<Product> GetAll()
{
return products;
}
public Product Get(int id)
{
return products.Find(p => p.Id == id);
}
public Product Add(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId++;
products.Add(item);
return item;
}
public void Remove(int id)
{
products.RemoveAll(p => p.Id == id);
}
public bool Update(Product item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = products.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
products.RemoveAt(index);
products.Add(item);
return true;
}
}
}
My question is, why is the interface written in such a way that it GetAll()returns IEnumerable<Product>if the implementation will specifically work with List<Product>?
, , - IProductRepository IEnumerable<Product> ( , , , , ).
, , :
public IEnumerable<Product> GetAll()
{
return products;
}
:
public List<Product> GetAll()
{
return products;
}
, public List<Product> GetAll() public IEnumerable<Product> GetAll()?
+4
2