Reputation: 215
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 = ""
?
Upvotes: 2
Views: 181
Reputation: 12934
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.
Upvotes: 7
Reputation: 38810
string my = "ABC";
Test test = new Test();
Note here, that there is no relationship between your Test
class and the string my
. I am not entirely sure what you are trying to achieve, but we could do it like this:
public class Test
{
private string _mystr;
private Action<string> _action;
public Test(Action<string> action)
{
_action = action;
}
// Let's make mystr a property
public string mystr
{
get { return _mystr; }
set
{
_mystr = value;
_action(_mystr);
}
}
}
Now you can do this:
string my = "ABC";
Test test = new Test((mystr) => { if(string.IsNullOrEmpty(mystr)) my = ""; });
test.mystr = my;
test.mystr = "";
Upvotes: 0
Reputation: 101768
Strings in .NET are immutable and don't work like that. One approach you could try is to use a mutable wrapper for the strings.
public class StringReference
{
public string Value {get; set;}
public StringReference(string value)
{
Value = value;
}
}
public class Test
{
internal StringReference mystr;
}
StringReference my = new StringReference("ABC");
Test test = new Test();
test.mystr = my;
test.mystr.Value = "";
// my.Value is now "" as well
Upvotes: 2