Consider the following:
public class EntityBase<TEntity>
{
public virtual void DoSomethingWhereINeedToKnowAboutTheEntityType()
{
}
}
public class PersonEntity : EntityBase<PersonEntity>
{
public override void DoSomethingWhereINeedToKnowAboutTheEntityType()
{
}
}
I added this into code and ran it and it worked ok, but I’m surprised that I can inherit a class who’s definition is based on the inheriting class.
When I tried it I was expecting either it not to compile, or to fail once actually called.
You can do something similar with an interface:
public interface IEntityBase<TEntity>
{}
public class PersonEntity : IEntityBase<PersonEntity>
{}
I’ve actually switched my code from the former to the later, using the interface, but I’m still curious why this works.
Careful – what you’re inheriting is a class whose definition involves an arbitrary
Type, is all. All of these are legal:All you’ve said in the definition of
EntityBaseis thatTEntityshould be a type – well,PersonEntityis a type, isn’t it? So why shouldn’t it be eligible to be aTEntity? No reason why not – so it works.You might be concerned about the order of definitions, but remember that within the unit of compilation, everything gets defined ‘at once’ – there’s no sense in which
PersonEntityneeds to be compiled ‘before’ anything else (including itself!) can refer to it. Indeed, you’re even allowedfor which no conceivable ‘order of compilation’ could work, if such a thing were needed.