Hy all, So I just want to work with generic and casting. But for some reason is does not work and I do not know why.
abstract class BaseModel {}
class NewModel : BaseModel {}
class BaseRepo<T> where T : BaseModel {}
class NewRepo : BaseRepo<NewModel> {}
class Test
{
public void TestMethod()
{
BaseRepo<BaseModel> t1 = new BaseRepo<BaseModel>();
BaseRepo<NewModel> t2 = new NewRepo();
BaseRepo<BaseModel> t3 = new BaseRepo<NewModel>();
// Cannot convert initializer type 'TestGeneric.BaseRepo<TestGeneric.NewModel> to target type 'TestGeneric.BaseRepo<BaseModel>'.
// Cannot implicitly convert type 'TestGeneric.BaseRepo<TestGeneric.NewModel>' to 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
// Type 'NewModel' doesn't match expected type 'BaseModel'.
// Cannot convert source type 'TestGeneric.BaseRepo<TestGeneric.NewModel>' to target type 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
BaseRepo<BaseModel> t4 = new NewRepo();
// Cannot convert initializer type 'TestGeneric.BaseRepo<TestGeneric.NewModel> to target type 'TestGeneric.BaseRepo<BaseModel>'.
// Cannot implicitly convert type 'TestGeneric.NewRepo' to 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
// Cannot convert source type 'TestGeneric.NewRepo' to target type 'TestGeneric.BaseRepo<TestGeneric.BaseModel>'.
}
}
I just do not understand why t3 and t4 throwing does exceptions meanwhile t1 and t2 works. Even is NewModel is a subclass of BaseModel the last two does not works.