Saturday, August 25, 2007

Pass by value or Pass by reference

Here is a simple example of parameter passing in C#..

   1: public class ParameterPassingSample
   2: {
   3:     public ParameterPassingSample()
   4:     {
   5:     }
   6:  
   7:     public void  CallingMethod()
   8:     {
   9:         StringBuilder sb1 = new StringBuilder("Test");
  10:         CalledMethod(sb1);
  11:         System.Diagnostics.Debug.Assert("Test test"==sb1.ToString(),"String equal");
  12:     }
  13:  
  14:     public void CalledMethod(StringBuilder sb2)
  15:     {
  16:         sb2.Append(" test");
  17:     }
  18: }

Since CalledMethod  function changed the sb value, it will easily give you an impression that Parameter is passed by reference. Actually, it's not.


parameter memory layour


Sb2 is a new string builder object, and it points to the same string builder object in memory. So, when CalledMethod change the value, the value which the original string object (sb1) refers also change. This doesn't mean "pass by reference", it is still "pass by value".  Here is another example to show this.



   1: public class ParameterPassingSample
   2: {
   3:     public ParameterPassingSample()
   4:     {
   5:     }
   6:  
   7:     public void  CallingMethod()
   8:     {
   9:         StringBuilder sb1 = new StringBuilder("Test");
  10:         CalledMethod(sb1);
  11:         System.Diagnostics.Debug.Assert("Test"==sb1.ToString(),"String equal");
  12:     }
  13:  
  14:     public void CalledMethod(StringBuilder sb2)
  15:     {
  16:         sb2 = null;
  17:     }
  18: }

Here , if sb2 changes to null, it doesn't affect the value of sb1. 


parameter memory layour


The difference between those two examples are "change the value the parameter points to" or "change the value of the parameter itself".

No comments: