9

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.

5
  • You already asked this here: stackoverflow.com/questions/2067725/…
    – user47589
    Jan 14, 2010 at 22:19
  • @yodaj007: This one cleans up his idea from that question. I've already voted to close the old one. Jan 14, 2010 at 22:23
  • It's been awhile since I've coded in C++. Your example only ensures that both a1 and a2 point to the same object in memory so changes in one are reflected in both, right? So it's not really copying to another A, right? Jan 14, 2010 at 22:30
  • nope. The *obj = is different from obj=. obj = changes the pointer while *obj copies.
    – user34537
    Jan 14, 2010 at 22:51
  • I had a similar sort of issue myself recently and came up with a generic method - it does use reflection: pmichaels.net/2016/03/04/… Mar 6, 2016 at 11:12

8 Answers 8

8

I have used binary serialization. Basically, serialize the instance to a memory stream. Then, deserialize it out of the memory stream. You will have an exact binary copy. It will be a deep copy, rather than a shallow copy.

class a = new ClassA();

class b = MySerializationMethod(a);

For a shallow copy you can use Object.MemberwiseClone

3
  • +1 for this method. We've used this many times and it works great.
    – womp
    Jan 14, 2010 at 22:23
  • It looks like Object.MemberwiseClone only works with the two classes are the same and within the class method? How might i program MySerializationMethod? It seems i'll be using reflection.
    – user34537
    Jan 14, 2010 at 22:35
  • someone posted it below: c-sharpcorner.com/UploadFile/sd_surajit/cloning05032007012620AM/… no reflection needed Jan 15, 2010 at 0:15
8

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 || dstF.IsLiteral)
                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);
        }
    }
5

Assuming A is just a simple class, you can do

A newA = instanceOfA.MemberwiseClone();

MemberwiseClone() is a shallow copy though, so if your class gets complex, with properties that are also reference types, this will not work for you.

2
  • 1
    Although this cannot be as fast as a non-reflection approach. Jan 14, 2010 at 22:14
  • Agreed. It can be more convenient and scalable than a custom approach however.
    – womp
    Jan 14, 2010 at 22:25
4

there is the ICloneable interface which offers up a Clone() method.

Clone on msdn.

4

Here's what somebody has already done...

Deep Copy in C# (Cloning for a user defined class)

3

Add the appropriate constructors:

class Foo
{
    public Foo(int a, string b)
    {
        A = a;
        B = b;
    }

    public Foo(Foo other)
    {
        A = other.A;
        B = other.B;
    }

    public int A { get; set; }
    public string B { get; set; }
}

You should also consider making it immutable, especially if you are considering making it into a struct. Mutable structs are evil.

Finally when you are inheriting from a class you don't need to copy the members from the base class into the subclass.

4
  • +1 if I had enough votes today. Immutable would imply no set properties, right? Jan 14, 2010 at 22:17
  • @lpthnc: private set would do it.
    – Bruno Reis
    Jan 14, 2010 at 22:19
  • Thanks. How would you declare that if you want to keep get as public - on the same line or separately? Jan 14, 2010 at 22:24
  • 1
    @Ipthnc: public int A { get; private set; }
    – Mark Byers
    Jan 14, 2010 at 22:26
2

We've used this code successfully:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Utility {
    internal static class ObjectCloner {
        public static T Clone<T>(T obj) {
            using (MemoryStream buffer = new MemoryStream()) {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(buffer, obj);
                buffer.Position = 0;
                T temp = (T)formatter.Deserialize(buffer);
                return temp;
            }
        }
    }
}

There may be other methods which work better, but perhaps this will help you

Chris

0

You can Clone, you can define a copy constructor. Why change class to struct just because in C++ you can do something in 10 characters. C# is different. Structs have advantages and disadvantages.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.