Generic Extension Method To Map Objects From One Type To Another

Introduction

Let me start with one scenario. Just imagine we have an object which has lots of public properties and we need to use only some properties of it for the user profile method. For example, we have a class Teacher_Interview and another class named Teacher_College.

public class TeacherInterview
{
    public int UID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Subject { get; set; }
}

public class TeacherCollege
{
    public int TID { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

Here, we have written both the classes. As we can see, we have a Teacher_Interview class that contains its public properties. Now, we need to use the Teacher_college class object and want the same values from the Teacher_Interview class object.

Example

Teacher_Interview ti = new Teacher_Interview()
{
    UID = 101,
    Name = "Faisal Pathan",
    Email = "[email protected]",
    Subject = ".NET"
};

Now, in a normal case, we copy/use the Teacher_Interview object value in Teacher_College like below.

Teacher_College tc = new Teacher_College()
{
    TID = ti.UID,
    Name = ti.Name,
    Email = ti.Email
};

Just think about what happens if we have 40-50 or more than 50 properties. In this case, we have to write the same line 40 to 50 times which is definitely a time-consuming and boring thing. It is also possible to forget to assign some of the properties which will result in an error.

So, what is the solution for that?

We can use System.reflection namespace and classes.

Here, I wrote a generic method, namely “MatchAndMap” which copies the same name properties from Teacher_Interview class object to the Teacher_College class object.

public static void MatchAndMap<TSource, TDestination>(this TSource source, TDestination destination)
    where TSource : class, new()
    where TDestination : class, new()
{
    if (source != null && destination != null)
    {
        List<PropertyInfo> sourceProperties = source.GetType().GetProperties().ToList();
        List<PropertyInfo> destinationProperties = destination.GetType().GetProperties().ToList();

        foreach (PropertyInfo sourceProperty in sourceProperties)
        {
            PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);

            if (destinationProperty != null)
            {
                try
                {
                    destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
                }
                catch (Exception ex)
                {
                    // Handle any exceptions that occur during property mapping here.
                    // You might want to log the exception or take appropriate action.
                }
            }
        }
    }
}

This method will work for us and map the properties having the same name. But, we will not call this method directly. We will call from another method which is mentioned below.

public static TDestination MapProperties<TDestination>(this object mapSource)
    where TDestination : class, new()
{
    var destination = Activator.CreateInstance<TDestination>();
    MatchAndMap(mapSource, destination);

    return destination;
}

The “Activator.CreateInstance” first creates an empty instance for our destination class and passes in the MatchAndMap method and then returns to the destination.

Now here, we think how to call or use this method. So, here is a way to use this method.

Var records = (Teacher_Interview_class_object).MapProperties<Teacher_College_class_object>();

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Faisal_Example.Extention
{
    public static class MyExtensions
    {
        public static void MatchAndMap<TSource, TDestination>(this TSource source, TDestination destination)
            where TSource : class, new()
            where TDestination : class, new()
        {
            if (source != null && destination != null)
            {
                List<PropertyInfo> sourceProperties = source.GetType().GetProperties().ToList();
                List<PropertyInfo> destinationProperties = destination.GetType().GetProperties().ToList();

                foreach (PropertyInfo sourceProperty in sourceProperties)
                {
                    PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);

                    if (destinationProperty != null)
                    {
                        try
                        {
                            destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
                        }
                        catch (Exception ex)
                        {
                            // Handle any exceptions that occur during property mapping here.
                            // You might want to log the exception or take appropriate action.
                        }
                    }
                }
            }
        }

        public static TDestination MapProperties<TDestination>(this object source)
            where TDestination : class, new()
        {
            var destination = Activator.CreateInstance<TDestination>();
            MatchAndMap(source, destination);

            return destination;
        }
    }
}

Conclusion

In this article, I explained how we can perform smart work instead of hard work to copy the same class object properties to another class object.

I hope this article will be helpful and useful somewhere in your project. Please give your valuable feedback and share with your friends so they can use this method.


Similar Articles