Dani
Dani

Reputation: 15069

c# Generics new() constraints with type: (new(T))

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;

Upvotes: 6

Views: 3882

Answers (3)

Tim Robinson
Tim Robinson

Reputation: 54734

There's no such thing as P : new(E), but you could have the caller supply a delegate that knows how to construct a P given an E:

public static List<P> ListConvert<E, P>(List<E> efList, Func<E, P> converter)
{
    List<P> pList = new List<P>();

    foreach (E item in efList)
    {
        P myItem = converter(item);
        pList.Add(myItem);
    }
    return pList;
}

However, if you're doing this, you may as well use LINQ: efList.Select(e => new P(e)).ToList().

Upvotes: 2

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74360

This is not possible. The new constraint only allows you to create objects via a public parameterless constructor.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500225

There's no such constraint. What you can do is have an extra parameter:

public static List<P> ListConvert<E, P>(List<E> efList, Func<E, P> func)

That way it isn't required to be a constructor, but you can pass in a delegate which calls the constructor:

ListConvert(list, x => new Foo(x))

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.

Upvotes: 8

Related Questions