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'
1 Answer. To explain I would say: SessionList is not an implementation of List interface. The others are concrete classes of List.
Overall, List is a concrete type that implements the IList interface.
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.
In C#, the LinkedList(T) class does not implement the IList(T) interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With