I tried a generic class conversion in a more complicated context first only to find out its not possible. So just for demonstration purpose I wrote this sample which is about the most general formulation of my problem I can think of, leaving out anything unnecessary:
using System;
using System.Collections.Generic;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
// problem
Generic<Sub> subvar = new Generic<Sub>();
Generic<Super> supervar;
supervar = (Generic<Super>)subvar; // <--fails
// reason for asking
List<Generic<Super>> list = new List<Generic<Super>>();
list.Add(supervar);
}
}
class Super { }
class Sub:Super { }
class Generic<T> where T : Super { }
}
So in general: Since every "Sub" is a "Super" I thought that every "Generic of Sub" is a "Generic of Super". So I expected that assigning a reference to a Generic<Sub>
to a variable of Generic<Super>
would be no problem, even without the explicit typecast.
But .NET Framework tells me this conversion is forbidden, why?
So, why would I want to do this? Suppose I would like to build a Collection that only accepts "Generics of anything", how would I do this circumventing the conversion?