acidzombie24 acidzombie24 - 1 month ago 6
C# Question

Copy a class to another?

I have

class A
{
public int a;
public string b;
}


How can i copy A to another A? In C++ i know i could do
*a1 = *a2;
. Is there something similar in C#? I know i could write a generic solution using reflection but i hope something exist already.

I'm considering changing A to a nullable struct.

Step 2 i'll need to do

class B : A {}
class C : A {}


and copy the base data from B to C.

Answer

Here is some simple code that works on any class, not just base.

    public static void DuckCopyShallow(this Object dst, object src)
    {
        var srcT = src.GetType();
        var dstT= dst.GetType();
        foreach(var f in srcT.GetFields())
        {
            var dstF = dstT.GetField(f.Name);
            if (dstF == null)
                continue;
            dstF.SetValue(dst, f.GetValue(src));
        }

        foreach (var f in srcT.GetProperties())
        {
            var dstF = dstT.GetProperty(f.Name);
            if (dstF == null)
                continue;

            dstF.SetValue(dst, f.GetValue(src, null), null);
        }
    }