Cast IList <string> a IList <object> falla en tiempo de ejecución
Tengo el siguiente programa corto de C #:
IList<string> listString = new List<String>();
IList<object> listObject;
listObject = listString;
Este programa no se compila. La última línea provoca el siguiente error de compilación:
No se puede convertir implícitamente el tipo 'System.Collections.Generic.IList' a 'System.Collections.Generic.IList'. Existe una conversión explícita (¿falta un elenco?)
Así que, he añadido el elenco:
listObject = (IList<object>)listString;
Ahora el programa compila correctamente, pero falla en tiempo de ejecución. UnInvalidCastException
Se plantea con el siguiente mensaje:
No se puede convertir el objeto de tipo 'System.Collections.Generic.List'1 [System.String]' para escribir 'System.Collections.Generic.IList'1 [System.Object]'.
O bien el reparto es ilegal y debe ser capturado por el compilador, o es legal y no debe lanzar una excepción en el tiempo de ejecución. ¿Por qué el comportamiento inconsistente?
ACLARACIÓN: No estoy preguntando por qué falla el reparto. Entiendo por qué tal casting es problemático. Estoy preguntando por qué falla el repartosolo en tiempo de ejecucion.