How to create a generic property mapper, that maps properties from one object to an other, without relying on inheritance, composition or reflection in C#

Lets say you want to generate a generic [PropertyMapper] class, that can map the properties of a TypeX instance to a TypeY instance without introducing inheritance, composition or reflection in C#.

Well you can use several libraries, like automapper etc. but when you want to do this by hand, you can start by looking at the following example. In this example the PropertyMapper class maps the Person.Name property to a TextBox.Text property:

using System;
using System.Web.UI.WebControls;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Rli.Research.Test
public class PropertyMapper
public void Map<TSource, TDestination>(TSource source, TDestination destination, Action<TSource, TDestination> mapAction)
mapAction(source, destination);
public class Person
public string Name { get; set; }
public class UnitTester
public void Map_should_copy_the_contents_of_the_property_person_name_to_the_textbox_text_property()
// Arrange.
var source = new TextBox();
var destination = new Person { Name = "John Do" };
Action<TextBox, Person> mapAction = (source1, destination1) => source1.Text = destination1.Name;
// Act.
var mapper = new PropertyMapper();
mapper.Map(source, destination, mapAction);
// Assert.
Assert.AreEqual(destination.Name, source.Text);

The unit test will succeed.


Generic TypeConverter

Of course you can map multiple properties in one "mapAction”, allowing to "convert" one type to an other, without relying on inheritance composition or reflection.



This code is not intended to be used for model to view binding, for this please use INotifyPropertyChanged and CallerInfoAttributes in C# 5.0: