1

I have an Abstract class that is implemented like this:

public abstract class BaseImplementation<T, U> : IHistory<T>
        where T : class, IEntity, new()
        where U : DbContext, new()

I understand that the generic argument <U> is an EF DbContext. I understand that the generic argument <T> must be a class that implements the IEntity Interface.

What is the "new()"? Must be a new instance of a given class? What is the purpose of that? Note that is declared in both <T> and <U>

Thank you.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
J_PT
  • 479
  • 4
  • 22

3 Answers3

3

From the docs:

"The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract."

I don't really have much more to add to this as I think the explanation above is sufficient.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
3

The new() is called a new constraint and it requires that the type argument has a public, parameterless constructor.

The benefit of using it is that you can create an instance of your generic type inside the class, without explicitly knowing the type passed in.

For example:

public PersonEntity : IEntity
{
    // public parameterless constructor
    public PersonEntity()
    {
    }
}

public abstract class BaseImplementation<T, U> : IHistory<T>
    where T : class, IEntity, new()
    where U : DbContext, new()
{
    public T CreateEntity() 
    {
        var entity = new T();  
        // entity will be the type passed to `T` when instantiating `BaseImplementation`
    }
}

Then usage would be something like:

public class PersonImpl : BaseImplementation<PersonEntity, DataContext>
{
    public void Method1()
    {
        var entity = CreateEntity();
        // entity is typeof(PersonEntity);
    }
} 
Steve
  • 9,335
  • 10
  • 49
  • 81
1

new() is a constraint specifying that the type argument must have a public parameterless constructor. For more information about the generic type constraint, see MSDN

cheer
  • 121
  • 4