I was doing some work with interfaces today, when I run into the following scenario. Given these two simple interfaces:
public interface IItem { }
public interface IInventory
{
ICollection<IItem> Items { get; }
}
I made a simple class to implement IInventory
, and noticed that this implementation is perfectly fine as written:
public class BasicInventory1 : IInventory
{
private Dictionary<int, IItem> items;
public ICollection<IItem> Items
{
get { return items.Values; }
}
}
But yet, this implementation requires a cast:
public class BasicInventory2 : IInventory
{
private Dictionary<int, IItem> items;
public ICollection<IItem> Items
{
get { return (ICollection<IItem>)items; }
}
}
Why does one require a cast and the other doesn't? Checking the object typing for both collections that are getting returned in either case confirms that they both in fact implement ICollection
.
I suspect there is some magic type conversions going on under the hood here, and therefore seems to have something to do with co/contravariance, but I don't quite see what exactly is going on.
Dictionary<int, IItem>
does not implement ICollection<IItem>
. Simple as that.
It wouldn't make sense to implement that interface because you cannot add to a dictionary without specifying a key. The interface does not make sense.
This is a runtime error because items could refer to a subclass of Dictionary so that the cast might be valid.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments