pointers - C# Object Reference : How can i do it? -


this class test

public class test {     public string mystr; } 

and call method :

  string = "abc";   test test = new test();   test.mystr = my;   test.mystr = ""; 

result of bit code above : my = "abc" , test.mystr = ""

how can set my empty string "" when change test.mystr = ""?

if understand correctly, want variables my , test.mystr linked, if 1 changes, other changes?

the answer simple: cannot!

a string immutable class. multiple references can point string instance, once instance modified, string instance created new value. new reference assigned variable, while other variables still point other instances.

there workarounds, suspect not happy it:

public class test {     public string mystr; }  test mytest1 = new test { mystr = "hello" }; test mytest2 = mytest1; 

now, if change mytest1.mystr, variable mytest2.mystr modified, because mytest1 , mytest2 same instances.

there other solutions these, come down same aspect: class holding reference string.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -