0 Comments

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; }
    }
    [TestClass]
    public class UnitTester
    {
        [TestMethod]
        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.

 

Note

This code is not intended to be used for model to view binding, for this please use INotifyPropertyChanged and CallerInfoAttributes in C# 5.0: http://awkwardcoder.blogspot.nl/2012/03/how-fast-is-callerinfoattributes-for.html

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts