New () in the method

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 new() keyword (in class Repo<T> ) do?

+4
source share
3 answers

This means that type T should expose the public constructor by default (without parameters). That is, you can build an instance of T using new T() . It can also expose other constructors, but this general restriction makes the default value mandatory.

+11
source

this means that the object must have a constructor without parameters.

see this.

+3
source

When you use the where keyword in a generic definition, you apply a generic attribute to a generic parameter. 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 explanation disguised as an answer , I thought I would try to help by clarifying a few things.

The code in the original question defines the interface that seems to be used by the incorporeal constructor. Between these two definitions, you have defined a common class that does not seem to do much.

Your question refers to the generic class, and the other two definitions are not related to the question and the answer.

+1
source

All Articles