Consider the following situation:
- A base class named
Result
. - A derived class of
Result
namedRBTResult
. A derived class of
RBTResult
namedResultNL
class Result {} class RBTResult : Result {} class ResultNL : RBTResult {}
There's a List of 'Result' which holds concrete instances of RBTResult. So far so good.
static void Main(string[] args) {
List<Result> results = new List<Result> {
new RBTResult(),
new RBTResult()
};
append<ResultNL>(results);
}
We pass that list to a generic function append<T>()
where the generic type T
is ResultNL
.
In append there is a loop casting every item in the list to the generic type argument but there an InvalidCastException
is thrown every time.
static void append<T>(List<Result> res) where T : Result
{
List<Result> l = new List<Result>();
foreach (var r in res)
{
try
{
_ = (T)r;
l.Add(r);
}
catch (InvalidCastException e) { }
}
}
I would say it should be possible to cast from RBTResult
to T
(ResultNL
) because it is a derived class, but it doesnt.
Why is that? How to make this work?