Value parameters
By default, parameters are value parameters. This means
that a new storage location is created for the variable in the function member
declaration, and it starts off with the value that you specify in the
function member invocation. If you change that value, that doesn't alter any
variables involved in the invocation.
For instance, if we have:
void Foo (StringBuilder x) { x = null;
}
...
StringBuilder y = new StringBuilder(); y.Append
("hello"); Foo (y); Console.WriteLine (y==null);
EXAMPLE using
System; using System.Text;
public class Example3 { // Note that Foo is
declared static here just // to make the sample app simple, so we don't
// need to instantiate the example class. This // has no bearing
on the parameter passing // discussed static void Foo
(StringBuilder x) { x = null; }
public static void Main (string[] args) {
StringBuilder y = new StringBuilder(); y.Append ("hello");
Foo (y); Console.WriteLine (y==null); }
}
Output: False
The value of y isn't changed just because x is set to
null. Remember though that the value of a reference type variable is the
reference - if two reference type variables refer to the same object, then
changes to the data in that object will be seen via both variables.
For example:
void Foo (StringBuilder x) { x.Append ("
world");
}
...
StringBuilder y = new StringBuilder(); y.Append
("hello"); Foo (y); Console.WriteLine (y);
EXAMPLE
using System; using System.Text;
public class Example4 { // Note that Foo is
declared static here just // to make the sample app simple, so we don't
// need to instantiate the example class. This // has no bearing
on the parameter passing // discussed static void Foo
(StringBuilder x) { x.Append (" world"); }
public static void Main (string[] args) {
StringBuilder y = new StringBuilder(); y.Append ("hello");
Foo (y); Console.WriteLine (y); }
}
Output: hello
world
|