Ilan
Ilan

Reputation: 999

Generic function and new constraint

How can I use two parameters while one inherits from IProject and other has a new() constraint? The following doesn't pass compilation with the "Cannot create an instance of the variable type 'T' because it does not have the new() constraint" error.

public static T CreateNewProject<T, V>(string token, string projectName) where V : IProject<T>, T new()
{
    T project = new T(); 
}

Upvotes: 2

Views: 2655

Answers (1)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

If you want to apply constraints to multiple parameters, then you need to add second where as:

where V : IProject<T> 
where T : new()

And also, you need to return something from your method:

public static T CreateNewProject<T, V>(string token, string projectName) 
    where V : IProject<T> 
    where T : new()
{
    return new T();
}

P.S: For applying new constraint, the type argument must have a public parameterless constructor.

Read This for more information.

Upvotes: 5

Related Questions