An object that is known to be a List<object>
might implement IList<string>
as well as IList<object>
, so it's possible that the cast can succeed. It can't in this case because we know that the statement is simply new List<object>()
, but the compiler doesn't consider that. You might've extended List<T>
and implemented the other, e.g.
// not recommended, but second cast works
public class MyWeirdList : List<object>, IList<string>
An object that is known to be a List<object>
cannot possibly also be a List<string>
, because you can only inherit from a single type.
public class MyWeirdList : List<object>, List<string> // compiler error
If List<T>
were sealed, both casts would be invalid, because then the compiler would know for sure that the class couldn't implement IList<string>
. You can try this by using this class instead:
public sealed class SealedList<T> : List<T> { }