Ricardo Rea
Ricardo Rea

Reputation: 29

C# inheritance template and caste

it's my first question, excuse my incompetence,

I am trying to declare an object that is created from the inheritance of the same class but it tells me that I cannot cast the object being inherited

abstract class BaseEntity{...}

abstract class BaseController<T> where T : Model.BaseEntity{...}

class DummyEntity : BaseEntity {...}

class DummyController : BaseController<DummyEntity> {...}

When I want to create an object, it indicates that it cannot be implicitly converted.

BaseController<BaseEntity> a = new DummyController();

Upvotes: 2

Views: 63

Answers (1)

Joelius
Joelius

Reputation: 4329

You cannot do that. This has something to do with covariance.

Imagine the BaseController<T> has a method Add(T entity).

Now you create an instance of DummyController. You can call Add(CowEntity entity) on this instance because DummyController inherits BaseController<CowEntity> so T is CowEntity.

Now if you were able to assign this to BaseController<BaseEntity> you would suddenly be able to call Add(BaseEntity entity) (because T is now BaseEntity, not CowEntity anymore).
This means you could add an instance of ChickenEntity (which has nothing to do with CowEntity, it's just another derived class of BaseEntity) to that base-controller which is actually an instance of BaseController<CowEntity>. Now suddenly an instance of BaseController<CowEntity> contains a ChickenEntity. You see that this doesn't make sense.

To solve this you need to read about interfaces and covariance (and contravariance).

Hope this helps :)

Upvotes: 2

Related Questions