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?
Your
MyStructureconsists of an object reference of typeMyClassand anint(Int32). The assignmentcopies just those data, the reference and the integer. No new instance of
MyClassis created. You can’t change that.If you want to copy, you can say
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 theClonemethod and not just assign.(By the way, the
MyStructureis a “mutable struct”. Many people discourage them. If you mark the fields ofMyStructureasreadonly, I think “many people” will be satisfied.)Addition: See also Answer to Can structs contain references to reference types in C#.