This is my custom collection declaration.
public interface IMenuCollection<T> : ICollection<T>
public class HTMLMenuCollection: IMenuCollection<HTMLMenu>
I am trying to cast to it from another collection IList<T>.
IList<HTMLMenu> htmlMenuList = new List<HTMLMenu>();
...
HTMLMenuCollection tempColl = (HTMLMenuCollection)htmlMenuList;
I have no idea why this won’t work. If I cast IList<T> to ICollection<T> it works just fine, but with this I get an invalid cast exception. What am I doing wrong?
Think of inheritance as a ‘is a’ relationship.
Then you can think of it as being because
HTMLMenuCollectionis aList<HTMLMenu>but not everyList<HTMLMenu>is aHTMLMenuCollection(sinceList<HTMLMenu>doesn’t inherit fromHTMLMenuCollection).The reason that you can cast from a List to IList to ICollection is the following:
and