Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new() in method

Tags:

c#

generics

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?

like image 509
user1479794 Avatar asked Dec 06 '22 13:12

user1479794


1 Answers

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.

like image 63
David M Avatar answered Jan 03 '23 07:01

David M