I'm using reflection to get a property that is a ICollection<TestCastChild>
and cast it as a ICollection<ICastBase>
. TestCastChild implement's ICastBase. When I try to cast the collection, the cast fails. I'm sure that I'm missing something simple. I can't see why this fails.
public interface ICastBase
{
int Id { get; set; }
}
public interface ICastChild : ICastBase
{
string Name { get; set; }
}
public abstract class TestCastBase : ICastBase
{
public int Id { get; set; }
}
public class TestCastChild : TestCastBase, ICastChild
{
public string Name { get; set; }
}
public class TestCastParent : TestCastBase
{
public virtual ICollection<TestCastChild> Children { get; set; }
}
Then to test:
[TestMethod]
public void TestCast()
{
var parent = new TestCastParent();
parent.Children = parent.Children ?? new List<TestCastChild>();
parent.Children.Add(new TestCastChild{Name = "a"});
parent.Children.Add(new TestCastChild { Name = "b"});
parent.Children.Add(new TestCastChild { Name = "c"});
var propInfos = parent.GetType().GetProperties();
foreach (var propertyInfo in propInfos)
{
if (propertyInfo.PropertyType.GetMethod("Add") != null)
{
var tmpVal = propertyInfo.GetValue(parent);
//This evaluates to null
var cast1 = tmpVal as ICollection<ICastBase>;
//This evaluates to null
var cast2 = tmpVal as ICollection<ICastChild>;
//This evaluates to the expected value
var cast3 = tmpVal as ICollection<TestCastChild>;
}
}
}