C# Automatic deep copy of struct

The runtime performs a fast memory copy of structs and as far as I know, it's not possible to introduce or force your own copying procedure for them. You could introduce your own Clone method or even a copy-constructor, but you could not enforce that they use them.

Your best bet, if possible, to make your struct immutable (or an immutable class) or redesign in general to avoid this issue. If you are the sole consumer of the API, then perhaps you can just remain extra vigilant.

Jon Skeet (and others) have described this issue and although there can be exceptions, generally speaking: mutable structs are evil. Can structs contain fields of reference types


One simple method to make a (deep) copy, though not the fastest one (because it uses reflection), is to use BinaryFormatter to serialize the original object to a MemoryStream and then deserialize from that MemoryStream to a new MyStruct.

    static public T DeepCopy<T>(T obj)
    {
        BinaryFormatter s = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            s.Serialize(ms, obj);
            ms.Position = 0;
            T t = (T)s.Deserialize(ms);

            return t;
        }
    }

Works for classes and structs.


As a workaround, I am going to implement the following.

There are 2 methods in the struct that can modify the contents of BoolArray. Rather than creating the array when the struct is copied, BoolArray will be created anew when a call to change it is made, as follows

public void ChangeBoolValue(int index, int value)
{
    bool[] Copy = new bool[4];
    BoolArray.CopyTo(Copy, 0);
    BoolArray = Copy;

    BoolArray[index] = value;
}

Though this would be bad for any uses that involved much change of the BoolArray, my use of the struct is a lot of copying, and very little changing. This will only change the reference to the array when a change is required.