Search code examples
c#value-typereference-type

Copy stucture's ref-type members by value


I have an structure and a class

public class MyClass
{
    public string name;
}

public struct MyStructure
{
    public MyClass classValue;
    public int intValue;
    public MyStructure(MyClass classValue, int intValue)
    {
        this.classValue = classValue;
        this.intValue = intValue;
    }
}

Elsewhere I write the following code:

MyClass class1 = new MyClass() { name = "AA" };
MyStructure struct1 = new MyStructure(class1, 4);
MyStructure struct2 = struct1;
struct1.classValue.name = "BB";  //struct2.classValue.name also change!

How can I make sure that every reference type member of a structure is copied by value in cases such as this?


Solution

  • Your MyStructure consists of an object reference of type MyClass and an int (Int32). The assignment

    MyStructure struct2 = struct1;
    

    copies just those data, the reference and the integer. No new instance of MyClass is created. You can't change that.

    If you want to copy, you can say

    MyStructure struct2 = new MyStructure(
        new MyClass { name = struct1.classValue, },
        struct1.intValue
        );
    

    Of course, if you need to do this a lot, you can write a Clone() method to do just this. But you will have to remember to use the Clone method and not just assign.

    (By the way, the MyStructure is a "mutable struct". Many people discourage them. If you mark the fields of MyStructure as readonly, I think "many people" will be satisfied.)

    Addition: See also Answer to Can structs contain references to reference types in C#.