Passing arguments by value
By default, arguments in C# are passed by value. This means a copy of the value is created when passed to the method:
class Test
{
static void Foo(int p)
{
p = p + 1; // Increment p by one.
Console.WriteLine(p); // Write p to screen.
}
static void Main()
{
int x = 8;
Foo(x); // Make a copy of x.
Console.WriteLine(x); // x will still be 8.
}
}
Assigning p a new value does not change the contents of variable x, because p and x reside in different memory locations.
Passing a reference-tupe argument by value copies the reference, but not the object. An example in the case of string builder; here Foo sees the same StringBuilder
object that main instantiated, but has an independent reference to it. So StrBuild and fooStrBuild are seperate variables that reference the same StringBuilder
object:
class Test
{
static void Foo(StringBuilder fooStrBuild)
{
fooStrBuild.Append("testing");
fooStrBuild = null;
}
static void Main()
{
StringBuilder StrBuild = new StringBuilder();
Foo(strBuild);
Console.WriteLine(StrBuild.ToString()); // "testing"
}
}
Because fooStrBuild is a copy of a reference changing its value does not change StrBuild.
Pass by reference
In the following, p and x refer to the same memory locations:
class Test
{
static void Foo(ref int p)
{
p = p + 1; // Increment p by one.
Console.WriteLine(p); // Write p to screen.
}
static void Main()
{
int x = 8;
Foo(ref x); // Make a copy of x.
Console.WriteLine(x); // x is now 9.
}
}
hence the value of p is changed.
Hope this helps.