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 thenew()
constraint on your class/method definition:Since you are using a parameter in the constructor, you can't use
new
, but you can use theActivator
instead and passother
as an argument: