Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Object Reference : How can i do it?

Tags:

c#

pointers

This is class Test

public class Test
{
    public string mystr;
}

And i call it from method :

  string my = "ABC";
  Test test = new Test();
  test.mystr = my;
  test.mystr = "";

Result of a bit code above are : my = "ABC" and test.mystr = ""

How can I set my to empty string "" when I change test.mystr = ""?

like image 405
Hùng Lê Xuân Avatar asked Jan 27 '26 13:01

Hùng Lê Xuân


1 Answers

If I understand correctly, you want the variables my and test.myStr to be linked, so if one changes, the other changes?

The answer is simple: It cannot!

A string is an immutable class. Multiple references can point to a string instance, but once this instance is modified, a string instance is created with the new value. So a new reference is assigned to a variable, while the other variables still point to the other instances.

There is a workarounds, but I suspect you will not be happy with it:

public class Test
{
    public string mystr;
}

Test myTest1 = new Test { myStr = "Hello" };
Test myTest2 = myTest1;

Now, if you change myTest1.myStr, the variable myTest2.myStr will also be modified, but that is simply because the myTest1 and myTest2 are the same instances.

There are other solutions like these, but the all come down to the same aspect: A class holding a reference to a string.

like image 159
Martin Mulder Avatar answered Jan 29 '26 02:01

Martin Mulder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!