Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I change the value of a variable which is a copy of another, it changes the original variable also

public class TestClass
{
    public int TestNumber;
    public string TestName;

    public TestClass(string name, int number)
    {
        TestName   = name;
        TestNumber = number;
    }
}

public class AnotherClass
{  
    TestClass Var1, Var2;

    void Start()
    {
         Var1 = new TestClass("Me", 1);
         Var2 = Var1;
         Var2.TestName = "aaa";
    }
}

When I debug the value of Var1.TestName I get "aaa" but originally it was "Me". How can I separate each var but still Var2 gets its initial values from Var1?

like image 425
Forenkazan Avatar asked Oct 30 '22 09:10

Forenkazan


1 Answers

Here is your problem:

Var1=new TestClass("Me",1);
Var2 = Var1;
Var2.TestName="aaa";

Var2 = Var1; is actually a reference copy! This means that the Var2 will take the address of Var1 and no matter what you modify in either of them, it will be visible in the other. To get that, I would recommend using a copy of Var2. To do so, create a method in your testClass class.

public testClass copy()
{
    testClass tC = new testClass(this.TestNumber, this.TestName);
    return tC;
}

Now you can assign the value like this: Var2 = Var1.copy();

like image 122
Simply Me Avatar answered Nov 15 '22 06:11

Simply Me