Possible Duplicate:
IList<Type> to IList<BaseType>
I am programming in C# using .NET 2.0 and I don't understand why the cast below results in a null reference.
If you have an IList<IChild>, why can't you cast it to an IList<IParent> where IChild implements IParent.
using System.Collections.Generic;
namespace InterfaceTest
{
public interface IParent
{
}
public interface IChild : IParent
{
}
public abstract class Parent : IParent
{
}
public sealed class Child : Parent, IChild
{
}
public sealed class Container
{
public IList<IChild> ChildInterfaceList
{
get;
set;
}
public Container()
{
ChildInterfaceList = new List<IChild>();
}
}
class Program
{
static void Main(string[] args)
{
Container container = new Container();
var childInterfaceList = container.ChildInterfaceList;
System.Diagnostics.Debug.Assert(childInterfaceList != null);
var parentInterfaceList = container.ChildInterfaceList as IList<IParent>;
//I don't expect parentInterfaceList to be null, but it is
System.Diagnostics.Debug.Assert(parentInterfaceList != null);
}
}
}