views:

49

answers:

3

I have a collection of objects which I pass as parameter to create objects of another type (one for one). I am doing this in many places (basically converting from data objects to business objects). I want to write a generic extension method to accomplish this. But I am stuck because I don't know how I can specify constraint that business object has a constructor taking data object as parameter. Following is code of my function:

public static IList<T> ConvertTo<A,T>(this IEnumerable<A> list) 
                    where T : new(A)/*THIS IS PROBLEM PART*/
{
    var ret = new List<T>();

    foreach (var item in list)
    {
        ret.Add(new T(item));
    }
    return ret;
}
+2  A: 

Unfortunately, this isn't allowed in C#. You can have a new() constraint that forces the type to have a default constructor, but that is the only constructor related constraint supported by .NET.

Your best option is probably to define an interface you can use, and constrain to the interface. Instead of trying to set the object at construction, you can have an "Initialize" style method that takes the "A" object, and call that.

Reed Copsey
Yes the interface way is nice and I can use it because I'm using T4 template to generate BOs so won't be too much work.
TheVillageIdiot
+1  A: 

I believe this question is similar and the answers would help you out: http://stackoverflow.com/questions/3327596/generic-method-instantiate-a-generic-type-with-an-argument

jasonh
+2  A: 

You can't constrain generic type constructors in this way (only to require a parameterless constructor), but you could take a delegate to do the construction:

public static IList<T> ConvertTo<A, T>(this IEnumerable<A> list, Func<A, T> constructionFunc)
{
    return list.Select(constructionFunc).ToList();
}

And use it like this:

var IList<T> converted = someSequence.ConvertTo(a => new T(a));
Lee
any example of function parameter? where should I define it in class T?
TheVillageIdiot