Reputation: 71
Having these classes:
public interface IDbContextFactory
{
DbContext GetContext();
}
public class Repo<T> : IRepo<T> where T : Entity, new()
{
protected readonly DbContext c;
}
public Repo(IDbContextFactory f)
{
c = f.GetContext();
}
What does the keyword new()
(in class Repo<T>
) do?
Upvotes: 4
Views: 146
Reputation: 35716
When you use the where
keyword on a generic definition you apply a type contraint to the generic paramater. The new()
constraint declares that the type, T
in this case, must have a default constructor. http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx
After reading your clarification disguised as an answer I thought I would try and help by clarifying a couple of things.
The code in your orginal question defines an interface that seemes to be used by a disembodied constructor. In between those two denfinitions you have defined a generic class which doesen't seem to do much.
Your question pertains to the generic class and the other two definitions are irrelavent to both the question and the answer.
Upvotes: 1
Reputation: 72860
It means that the type T
must expose a public, default (i.e. parameterless) constructor. That is, you will be able to construct an instance of T
with new T()
. It can expose other constructors as well, but this generic constraint makes the default one mandatory.
Upvotes: 11
Reputation: 55022
it means, the entity should have a parameterless public constructor.
see this.
Upvotes: 3