Simple object mapper using reflection

Copy property values from one object to another using reflection

  • Share

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;

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

  • Share


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.

Comments for this article

comments powered by Disqus