1

I am trying to deep copy a complex object that has some date properties. I am getting "The value '' could not be converted to a valid date" error. I am using below code for copying:-

private static object CloneProcedure(Object obj)
{
    if (type.IsPrimitive || type.IsEnum || type == typeof(string))
    {
        return obj;
    }
    else if (type.IsClass || type.IsValueType)
    {
        object copiedObject = Activator.CreateInstance(obj.GetType());
        // Get all PropertyInfo.
        PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        foreach (PropertyInfo property in properties)
        {
            object propertyValue = property.GetValue(obj);
            if (propertyValue != null && property.CanWrite && property.GetSetMethod() != null)
            {
                property.SetValue(copiedObject, CloneProcedure(propertyValue));
            }
        }
    }
}

Am I missing something?

Kavya Shetty
  • 185
  • 2
  • 14

1 Answers1

0

You are not returing anything if your if is false.

This code is working in a .Net 4.5.2 Console application :

public class Program
{
    public static void Main()
    {
        ComplexClass t = new ComplexClass()
        {
            x = DateTime.Now
        };
        object t2 = CloneProcedure(t);
        Console.WriteLine(t.x);
        Console.ReadLine();
    }
    private static object CloneProcedure(Object obj)
    {
        var type = obj.GetType();
        if (type.IsPrimitive || type.IsEnum || type == typeof(string))
        {
            return obj;
        }
        else if (type.IsClass || type.IsValueType)
        {
            object copiedObject = Activator.CreateInstance(obj.GetType());
            // Get all PropertyInfo.
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (PropertyInfo property in properties)
            {
                object propertyValue = property.GetValue(obj);
                if (propertyValue != null && property.CanWrite && property.GetSetMethod() != null)
                {
                    property.SetValue(copiedObject, CloneProcedure(propertyValue));
                }
            }
        }
        return obj;
    }

    public class ComplexClass
    {
        public DateTime x { get; set; }
    }
}
Christoph Sonntag
  • 4,459
  • 1
  • 24
  • 49