views:

20

answers:

1

I have some objects like user, address and so on, and Im converting them to business objects using extension methods:

public static UserModel ToPresentationForm(this User pUser)
    {
        return new UserModel
        {
          ...
          map data
          ...
        };
    }

Also I need to convert strongly typed collections and usually I have the following code:

public static List<UserModel> ToPresentationForm(this List<User> pUserColl)
    {
        return pUserColl.Select(x => x.ToPresentationForm()).ToList();
    }

I was thinking, what if I add some interface, like IPresentationForms and will be able to use it, to write method like

public static List<T> ToPresentationForm(this List<IPresentationForms> pTemplate)
    {
        return pUserColl.Select(x => x.ToPresentationForm()).ToList();
    }

Not sure how to provide parameter to method type to make it generic. So the actual question is, how to do that.

P.S. Im using C# 4.0

+1  A: 

Unfortunately since there is likely no relationship between User and UserModel, there is no way to create an interface to do what you want.

On the other hand, let's say that User and UserModel both implement the IUser interface. Then you could have an interface like this:

interface IPresentationForms<T>
{
    T ToPresentationForm();
}

And you could define User like this:

class User: IUser, IPresentationForms<IUser>
{
    public IUser ToPresentationForm()
    {
        return new UserModel(...);
    }
    .... // implement IUser
}

That could enable you to define ToPresentationForm something like this:

public static List<T> ToPresentationForm<T>(this IEnumerable<T> pTemplate)
    where T : IPresentationForms<T>
{    
    return pTemplate.Select(x => x.ToPresentationForm()).ToList();    
}    

That's a lot of work to do to avoid a few extra methods.

Gabe
What do you mean by no interface between 2 classes?
Yaroslav Yakovlev
Since your definition of `UserModel` likely doesn't mention `User` anywhere, you cannot do what you want. If `UserModel` implemented `IModel<User>` (for example), maybe you could make your interface.
Gabe
Ok, what and should be implemented to make it convert all collections with one method? :-). I don`t mind to vary things a little bit, just I think as how it works now it`s not good as I`m doing copypaste, just to specify type.
Yaroslav Yakovlev
I don't think there is an easy fix here. If you post the declarations of `User` and `UserModel` maybe we can see if this is possible, but it likely isn't.
Gabe
actually it`s 2 classes with identical list of properties. Let it be FirstName and LastName for example.
Yaroslav Yakovlev