-2

Im making a function that maps two diferent objects (with equivalent properties and types) using reflection and generic objects (T). My function works well with objects with simple properties like int or string types but now I have to add support for object properties or lists wihtin an object. Can I do this recursively or is it not posible ? I can't post the code for work reasons. The active code is the following:

    public static T MapObjects<T>(object sourceObject) where T : new()
    {
        T destObject = new T();

        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            if (targetObj == null)
                continue;

            targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
        }
        return destObject;
    }

Can I modify this function to call itself when the property is an object ?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86

1 Answers1

0

You can look at Protobuf.net (which can be installed as Nuget package). It is based on Google protocol buffer and is fairly easy to serialize and deserialise objects or copy objects.

Protobuf-Net as copy constructor

https://www.c-sharpcorner.com/article/serialization-and-deserialization-ib-c-sharp-using-protobuf-dll/

Getting started with protobuf-net

Gauravsa
  • 6,330
  • 2
  • 21
  • 30