C# – Generic Constructor with New Type Constraint

c++genericstype-constraints

I have 2 types of objects, Database models and normal system models.

I want to be able to convery the model into Database model and vice versa.

I have the following method I wrote:

 public static E FromModel<T, E>(T other) 
            where T : sysModel
            where E : dbModel
{
     return new E(other);
}

basically both sysModel and dbModel are abstract.

dbModel have lots of inherting classes which all have copy constructors.

Im receiving :

Cannot create an instance of type parameter 'E' becauase it does not
have the new() constraint

Im aware that technically sometimes I dont have a matching constructor for every value of T, at least that whats the debugger know.

I also tried adding the where E : dbModel, new() constraint, but its just irrelevant.

Is there a way to convert model into another model using generic method and using parameters?

Thanks.

Best Answer

To use new on a generic type, you would have to specify the new() constraint on your class/method definition:

public static E FromModel<T, E>(T other) 
        where T : sysModel
        where E : dbModel, new()

Since you are using a parameter in the constructor, you can't use new, but you can use the Activator instead and pass other as an argument:

public static E FromModel<T, E>(T other)
    where T : sysModel
    where E : dbModel
{
    return (E)Activator.CreateInstance(typeof(E), new[]{other});
}