Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

I am having 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

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

Both Manufacturer and Product are of type IHierarchicalEntity. Why is it not taking the List<Product> as List<IHierarchicalEntity> ?

like image 410
SaravananArumugam Avatar asked Feb 23 '23 19:02

SaravananArumugam


2 Answers

This conversion is not possible, otherwise you could add a OtherHierarchicalEntity to List<Product> so its not safe. You can cast explicitly and return a new list:

  return Products.Cast<IHierarchicalEntity>().ToList();
like image 90
BrokenGlass Avatar answered Mar 29 '23 23:03

BrokenGlass


Try doing:

return Products.ToList<IHierarchicalEntity>();
like image 28
Dylan Smith Avatar answered Mar 29 '23 23:03

Dylan Smith