0

I am trying to do something simple: creating an instance with generics. I get an error saying that I cannot create an instance because I do not have the new constraint. However, I do have it on my return statement! Any thoughts?

public IAction CreateAction<TA, TP>(ActionParamBase param)
            where TA : IAction
            where TP : ActionParamBase
        {
            Ensure.That(param).Is<TP>();

            return new TA { Param = param as TP };
        }
AST
  • 211
  • 6
  • 18

2 Answers2

5

You have to specify the new() constraint on the TA type parameter in order to be able to call the constructor:

public IAction CreateAction<TA, TP>(ActionParamBase param)
        where TA : IAction
                 , new()
        where TP : ActionParamBase
    {
        ...
    }

Only then it knows (and forces) that TA has a parameterless constructor.

(Just a small note: it only works for parameterless constructors, not for constructors having arguments. In this case you are fine since you use initializers)

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
3

What it means is having new in the constraint of your TA part. See this SO post for reference, then see code below: Passing arguments to C# generic new() of templated type

public IAction CreateAction<TA, TP>(ActionParamBase param)
        where TA : IAction, new()
        where TP : ActionParamBase
    {
        Ensure.That(param).Is<TP>();

        return new TA { Param = param as TP };
    }
Community
  • 1
  • 1
GEEF
  • 1,175
  • 5
  • 17