I’m building a little helper to turn EF4 objects to POCOs.
(I know there is AutoMapper, but I’m having a c# dilemma at this time)
How can I make this work (the where P: new(E) is not legal
I wish to make sure the P (POCO) class as a constructor that takes the E class
(hence handling the transformation)
How can I make this work ?
How can I make a generic function in C# that can take a new(type) constraint ?
public static List<P> ListConvert<E, P>(List<E> efList) where P: new(E)
{
List<P> pList = new List<P>();
foreach (E item in efList)
{
P myItem = new P(item);
pList.Add(myItem);
}
return pList;
There’s no such constraint. What you can do is have an extra parameter:
That way it isn’t required to be a constructor, but you can pass in a delegate which calls the constructor:
I have a blue-sky idea which would enable constructor constraints, called “static interfaces” – these would only be useful for generic constraints, but would also enable some operator use cases.