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 };
        }
3
  • You need to do this: where TA : class, new() Check: stackoverflow.com/questions/4737970/… Commented Jul 30, 2015 at 14:24
  • TA is a generic interface.. you can't create an instance of interfaces Commented Jul 30, 2015 at 14:24
  • ok guys thanks for your help ! it worked! => where TA : IAction, new() Commented Jul 30, 2015 at 14:25

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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 };
    }

2 Comments

it's complaining about TA, not TP
Yea sorry I typod that when I initially typed it ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.