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>
?
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();
Try doing:
return Products.ToList<IHierarchicalEntity>();
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