While I can upcast a string to an object, I cannot upcast an IList of strings to an IList of objects. How come? What to do now other that coping all items to a new IList?
static void ThisWorks() { IList<object> list = new List<object>(); list.Add('I can add a string since string : object'); } static void ThisDoesNotWork() { // throws an invalid cast exception IList<object> list = (IList<object>) new List<string>(); list.Add('I'm never getting here ... why?'); }
Look at it like this: while a banana is a fruit, a basket of bananas is not a basket of fruit, since you can add oranges to the latter, but not the former. Your
List<string>has stronger constraints than aList<object>.Casting should always respect Liskow. For containers and iterators which do not admit modification, such casting is safe, but once things can be changed, you are skating close to the thin ice.