Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is not possible to use IList<T> in interface definition and List<T> in inplementation?

Tags:

c#

Why it is not possible to use IList in interface definition and then implement this property using List? Am I missing something here or just C# compiler doesn't allow this?

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

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

compiler says Error 82 'Category' does not implement interface member 'ICategory.Products'. 'Category.Products' cannot implement 'ICategory.Products' because it does not have the matching return type of 'System.Collections.Generic.IList'

like image 703
Ludek Avatar asked Dec 16 '10 08:12

Ludek


People also ask

Which of the following is not implemented using List T interface?

1 Answer. To explain I would say: SessionList is not an implementation of List interface. The others are concrete classes of List.

Does List implement IList?

Overall, List is a concrete type that implements the IList interface.

Should I use List or IList?

Basically, if you want to create your own custom List , say a list class called BookList , then you can use the Interface to give you basic methods and structure to your new class. IList is for when you want to create your own, special sub-class that implements List.

Which of the following interfaces is are not implemented by LinkedList class?

In C#, the LinkedList(T) class does not implement the IList(T) interface.


1 Answers

Change your code to:

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>(); } }        
}

You cannot change the signature of an interface method when you implement it.

like image 131
Martin Liversage Avatar answered Nov 15 '22 03:11

Martin Liversage