0

I am trying to implement object deep/shallow cloning service using Reflection. Using the function Clone<T> Simple class is being copied with all the required fields, but in case of SimpleStruct Computed field does not get copied.

What is the difference between struct and class when defining read-only fields, and how this can be solved ?

Thanks in advance.

public T Clone<T>(T source)
{
    var obj = Activator.CreateInstance<T>();
    var type = source.GetType();

    foreach (var property in type.GetProperties())
    {
        if (!property.IsValid())
            continue;

        if (property.SetMethod != null)
        {
            property.SetValue(obj, property.GetValue(source));
        }
    }

    foreach (var field in type.GetFields())
    {
        if (field.IsPublic == false || !field.IsValid())
            continue;

        field.SetValue(obj, field.GetValue(source));
    }

    return obj;
}

public struct SimpleStruct
{
    public int I;
    public string S { get; set; }
    [Cloneable(CloningMode.Ignore)]
    public string Ignored { get; set; }

    public string Computed => S + I;

    public SimpleStruct(int i, string s)
    {
        I = i;
        S = s;
        Ignored = null;
    }
}

public class Simple
{
    public int I;
    public string S { get; set; }
    [Cloneable(CloningMode.Ignore)]
    public string Ignored { get; set; }
    [Cloneable(CloningMode.Shallow)]
    public object Shallow { get; set; }

    public string Computed => S + I + Shallow;
}
Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27
  • 1
    First, there's no such thing as an expression bodied *field*. 2nd, you can't set the value of a computed/readonly *property* (struct or class), as it has no setter so I think you're either confused or not explaining properly what you mean. 3rd you'll have issues setting the fields/properties of a struct without first boxing the value to an object and then casting back and reassigning the value. See https://stackoverflow.com/q/6280506/491907. 4th, You ask about read-only fields, yet your code doesn't have any. Finally, you should show the definition of IsValid() as that might be important. – pinkfloydx33 Sep 30 '18 at 10:11
  • There is no point in copying computed properties, as their value is computed by the value of the other fields and properties. Also, GetFields() will only return public fields, so there is no need to check for IsPublic. As for your other question: there is no difference for readonly fields between structs and classes and neither does your code shows any such fields. So what do you want so solve there? – ckuri Sep 30 '18 at 12:07

0 Answers0