Return to Snippet

Revision: 66893
at July 17, 2014 06:06 by rralhan


Initial Code
public static void ShallowCopy(Object dest, Object src)
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
        FieldInfo[] destFields = dest.GetType().GetFields(flags);
        FieldInfo[] srcFields = src.GetType().GetFields(flags);

        foreach (FieldInfo srcField in srcFields)
        {
            FieldInfo destField = destFields.FirstOrDefault(field => field.Name == srcField.Name);

            if (destField != null && !destField.IsLiteral)
            {
                if (srcField.FieldType == destField.FieldType)
                    destField.SetValue(dest, srcField.GetValue(src));
            }
        }
    }

Initial URL


Initial Description
Copy from one object to another of the same type

Initial Title
Clone from one object to another using Reflection

Initial Tags
copy

Initial Language
C#