I am learning Nhibernate 3.0. In one of the sample code examples, it creates an abstract base entity class:
public abstract class Entity<T> where T : Entity<T>
then, make the Customer entity inherit from the Entity base class:
public class Customer : Entity<Customer>
I understand it’s an abstract generic class, and it is using the where keyword to make sure the type T is Entity<T>, this is where I get confused.
Customer inherits from “Entity<Customer>“, this “Entity<Customer>” takes “Customer” as T, but this Customer is not “Entity<T>“.
Please help me to understand this, I’m really confused by this generic class.
You saidThat doesn’t make any sense because that’s what inheritance means. It establishes an “is a” relationship. So in fact a
Customeris anEntitySorry that was based on the code with the generics stripped out because it wasn’t in a code block.
The same principle is still valid though. It’s just a little confusing because it looks like it’s a recursive definition, but it’s not.
Think of it as
Customerinherits fromEntityThere just happens to be methods or fields that depend on the generic parameter being itself e.g.Customer. I’m not familiar with NHibernate so I don’t know what the rest ofEntity<T>looks like, but I imagine it has some methods that use it’s own type as a generic parameter.Say for instance it has a method called
that returned a list of it’s own instances. It needs that method to return the concrete type rather than the base type. So in the
Customerclass, that method would beIf it didn’t have the generic parameter, it could only return
IEnumerable<Entity>That’s just an example of how it could be used, I don’t know how it’s actually used.