c# - If string is reference type, why pass by reference is not happening? -


i had read article http://www.albahari.com/valuevsreftypes.aspx

as per this, int value type , form example of reference type.

point mypoint = new point (0, 0);      // new value-type variable form myform = new form();              // new reference-type variable string mystringval="test"; test (mypoint, myform);                // test method defined below  void test (point p, form f) {       p.x = 100;                       // no effect on mypoint since p copy       f.text = "hello, world!";        // change myform’s caption since                                        // myform , f point same object       f = null;                        // no effect on myform } 

so instead of form variable myform, if pass string value function test, change original value declared outside?

also benefit of keeping string reference type, if, anyhow value saved in stack , reference stored in heap?

if pass string value function test, change original value declared outside?

no, neither did value of myform change, myform variable still points/refers same form object (the object created via new form()).

in test method, when called:

f.text = "hello, world!"; 

you did not change variable f, changed f.text different.

in other words, changing property on object both f , myform refer to. still f , myform refer same original object.

note when changed f null, variable myform did not change. now, f refers nothing, myform variable still refers original object.

if want change original myform variable (make point/refer form object) or mystringval (make refer string) pass them test method reference this:

void test (point p, ref form f) {     ... }  void test (point p, ref string s) {     ... } 

Comments