Why is it impossible to use IList <T> in an interface definition and List <T> in an implementation?

Why is it impossible to use IList in an interface definition and then implement this property using List? Am I missing something here or is the C # compiler just not resolving this?

public interface ICategory
{
    IList<Product> Products { get; }
}

public class Category : ICategory
{
    public List<Product> Products { get { new List<Product>(); } }        
}

the compiler says that error 82 'Category' does not implement the interface member 'i. category.Products'. "Category. Products" cannot implement "ICategory.Products" because it does not have the appropriate return type "System.Collections.Generic.IList"

+5
source share
3 answers

, . , , API. -, :

public interface ICategory
{
    IList<Product> Products { get; }
}

public class Category : ICategory
{
    IList<Product> ICategory.Products { get { return Products ; } }
    public List<Product> Products { get { ...actual implementation... } }        
}
0

:

public interface ICategory
{
    IList<Product> Products { get; }
}

public class Category : ICategory
{
    // Return IList<Product>, not List<Product>
    public IList<Product> Products { get { new List<Product>(); } }        
}

.

+8

It will work

public interface ICategory<out T> where T:IList<Product>
    {
        T Product { get; }
    }

public class Category : ICategory<List<Product>>
    {
        public List<Product> Products
        {
            get
            {
                throw new NotImplementedException();
            }
        }
    } 

Although difficult, but possible.

0
source

All Articles