TL;DR: If List<T> implements ICollection<T>, and Facility implements IAmAHierarchyNode, why can't I implicitly convert List<Facility> to ICollection<IAmAHierarchyNode>?
I'm getting an error of "Cannot implicitly convert type 'Foo' to 'Bar'. An explicit conversion exists (are you missing a cast?)"
Here's the code:
public interface IAmAHierarchyNode<IdType> {
IdType Id {
get;set;
}
ICollection<IAmAHierarchyNode<IdType>> Children {
get;
}
IAmAHierarchyNode<IdType> Parent {
get;set;
}
}
public class Network : IAmAHierarchyNode<Guid> {
public List<Facility> Facilities
{
get;set;
}
// This is where it's making me do an explicit conversion. But why?
public ICollection<IAmAHierarchyNode<Guid>> Children => Facilities;
public IAmAHierarchyNode<Guid> Parent {
get => throw new InvalidOperationException ();
set => throw new InvalidOperationException ();
}
}
public class Facility : IAmAHierarchyNode<Guid> {
public Network Network {
get;set;
}
public Guid NetworkId {
get;set;
}
public ICollection<IAmAHierarchyNode<Guid>> Children {
get => throw new NotImplementedException ();
}
public IAmAHierarchyNode<Guid> Parent {
get => Network;
set => throw new NotImplementedException ();
}
}
Here's what I've found so far in my research:
This SO question is the closest I've found. The second answer there says
You can only convert List<T1> to ICollection<T2> if the types T1 and T2 are the same.
So I'm converting from List<Facility> to ICollection<IAmAHierarchyNode>. My Facility class implements IAmAHierarchyNode, so I don't understand why they wouldn't be considered the same.
Sadly, this SO question is a typo on the OP's part. This one is in reference to explicit interface implementations and the answers there would lead me to think that I shouldn't be having a problem.