Search code examples
c#classunity-game-enginereference-type

(C#) How to copy classes by value type and not reference type?


Take the following code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyClass
{
    public int myNumber;
}

public class Test : MonoBehaviour
{
    MyClass class1 = new MyClass();
    MyClass class2 = new MyClass();

    void Start()
    {
        class1.myNumber = 1;
        class2 = class1;
        class2.myNumber = 2;

        Debug.Log(class1.myNumber); //output: 2 (I'd want it to output 1!!!)
    }
}

Now, if I understood correctly, in C# classes are a reference type and not a value type, so this behavior is desired.
However, what would I need to do to not make it so? What could I do to make a normal value assignment without "linking" the two classes together?

I realize I could replace line 18 with this:

class2.myNumber = class1.myNumber;

And it would do what I want (since I'm assigning a value type and not a reference type), but it's kinda inconvenient for my case... in my real script the class has several sub-elements that I need to copy in many different places.

Is there a one-line method to copy a class to a new one, without it being linked by reference to the original one but by creating a new independent class?


Solution

  • Perform a Deep or Shallow Copy depending on your needs. https://learn.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8