Hi,
Could anyone help me with the line where TEntity : class, IEntity, new()
in the following class declaration.
public abstract class BaseEntityManager<TEntity>
where TEntity : class, IEntity, new()
Thanks for your help in advance.
Hi,
Could anyone help me with the line where TEntity : class, IEntity, new()
in the following class declaration.
public abstract class BaseEntityManager<TEntity>
where TEntity : class, IEntity, new()
Thanks for your help in advance.
where TEntity : ...
applies constraints to the generic parameter TEntity. In this case, the constraints are:
class: The argument to TEntity must be a reference type
IEntity: The argument must be or implement the IEntity interface
new(): The argument must have a public parameterless constructor
Where is a generic type constraint. That lines reads that the type TEntity must be a reference type as opposed to a value type, must implement the interface IEntity and it must have a constructor that takes no parameters.
The where
keyword after the class declaration restrict what type the generic TEntity
could be. In this case TEntity
must be a class (meaning it can't be a value type like int
or DateTime
), and it must implement the interface IEntity
. The new()
constraint indicates that methods inside this class have the ability to call the default constructor of the generic class represented by TEntity
(e.g. new TEntity()
)
What's the question ?
Let me take at shot at what i think the question is. The constraint ensures that you can only subclass BaseEntityManager with a generic parameter which is a reference type implementing IEntity and containing a parameterless constructor.
E.X.
public class Product : IEntity {
public Product() {}
}
public class Wrong {
public Wrong() {}
}
public class WrongAgain : IEntity {
private Wrong() {}
}
// compiles
public ProductManager : BaseEntityManager<Product> {}
// Error - not implementing IEntity
public WrongManager : BaseEntityManager<Wrong> {}
/ Error - no public parameterless constructor
public WrongAgainManager : BaseEntityManager<WrongAgain> {}
see link text