Simple object mapper using reflection

Copy property values from one object to another using reflection

Dealing with models and POCO classes in MVC sometimes require to map properties from one object to another because they have some properties of the same name and type.

This also can be a case when you are loading a model class from some other source and you need to transform it to your type with some additional properties, but also a bunch of properties with values from the source object instance.

For example you have a class fro tweets. You request tweets from Twitter API and you will get object with a lot of data which they might not be interesting for you.

You also might want to take some values from Facebook account and merge them in one object with some values you got previously from Twitter.

Luckily, we can easily do this using reflection.

The following code is a simple mapper which maps all the properties from source object to target object but only in case that property names match and property types match as well.

        public static object MapObjects(object source, object target)
        {
            foreach (PropertyInfo sourceProp in source.GetType().GetProperties())
            {
                PropertyInfo targetProp = target.GetType().GetProperties().Where(p => p.Name == sourceProp.Name).FirstOrDefault();
                if (targetProp != null && targetProp.GetType().Name == sourceProp.GetType().Name)
                {
                    targetProp.SetValue(target, sourceProp.GetValue(source));
                }
            }
            return target;
        }
    
Note

Reflection is very expensive operation, so try to avoid it for he performance critical scenarios and applications

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article