Gal Segal's Blog

Thoughts of a programmer with a soul

Aug 30

Object Mapper Extension Method

Tags: ,

sunflower by pforty

Many times I need a small piece of code that will help me map one object to another. I see it a lot when dealing with view models : taking a business object and modeling it to serve the needs of the presentation layer.

There are many solutions to this problem:

  1. Target objects with a constructor that take the source object as parameter
  2. A factory method that does it.
  3. Just a simple piece of code that does the mapping.

When dealing with large applications where this process occurs many times, I think a generic procedure should take place. I also keep in mind the need to keep these object ready for serialization. So I came up with a simple extension method:

public static TTarget MapTo<TSource, TTarget>(this TSource source, Func<TSource, TTarget> mapper)
   where TSource : class
   where TTarget : class
{
   return mapper.Invoke(source);
}

and usage:

public class Source
{
    public string SourceName { get; set; }
}

public class Target
{
    public string TargetName { get; set; }
}
Source source = new Source()
{
    SourceName = "source"
};

Target target = source.MapTo(x =>
{
new Target() { TargetName = x.SourceName };
});
Back to top