Cannot implicitly convert type 'System.Collections.Generic.List <Library.Product>' to 'System.Collections.Generic.List <Library.IHierarchicalEntity>'

Possible duplicate:
In C #, why can't a List <string> object be stored in a list <object> variable

I have the following code.

public class Manufacturer : IHierarchicalEntity { public string ManufacturerName { get { return _manfuacturerName; } set { _manfuacturerName = value; } } private string _manfuacturerName; public List<Product> Products { get { return _products; } } private List<Product> _products; #region IHierarchicalEntity Members public List<IHierarchicalEntity> Children { get { return Products; //This is where I get the compiler error } } #endregion } public class Product : IHierarchicalEntity{} public interface IHierarchicalEntity { List<IHierarchicalEntity> Children { get; } } 

I get a compiler exception that

You cannot implicitly convert the type System.Collections.Generic.List<Library.Product> to System.Collections.Generic.List<Library.IHierarchicalEntity>

Both manufacturers and products are of type IHierarchicalEntity. Why doesn't it accept List<Product> as List<IHierarchicalEntity> ?

+4
source share
2 answers

This conversion is not possible, otherwise you can add OtherHierarchicalEntity to the List<Product> so that it is not safe. You can explicitly specify and return a new list:

  return Products.Cast<IHierarchicalEntity>().ToList(); 
+7
source

Try to do:

 return Products.ToList<IHierarchicalEntity>(); 
+1
source

All Articles