I encounter something maybe possible, but does not work.
Here is sample class,
abstract class BaseModel { }
abstract class BaseViewModel<T> where T : BaseModel
{
protected T model;
}
class ModelA : BaseModel { }
class ViewModelA : BaseViewModel<ModelA> { }
and now I try to do
class Program
{
static void Main(string[] args)
{
var collection = new List<BaseViewModel<BaseModel>>();
collection.Add(new ViewModelA());
}
}
Intuitively, it looks to be work. However it does not possible to add ViewModelA.
I want to know why this is not possible, and work around of this situation.
BaseViewModel<BaseModel>must be able to handle anything that inherits fromBaseModel. You are passing it aViewModelA, which can only handle a subset of things that inherit fromBaseModel, i.e. objects that inehrit fromModelA. So the assignment is not allowed.collection.Add(AnotherViewModel).collection.Add(AnotherViewModel)with the restriction to inheritBaseViewModel<T> where T : BaseModel. I understand it could be a design problem but I was curious why it does not working.