Assume the following code, without any ref
keyword, that obviously won't replace the variable passed, since it's passed as value.
class ProgramInt
{
public static void Test(int i) // Pass by Value
{
i = 2; // Working on copy.
}
static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(i);
Console.WriteLine(i);
Console.Read();
// Output: 1
}
}
Now to have that function working as expected, one would add the ref
keyword as usual:
class ProgramIntRef
{
public static void Test(ref int i) // Pass by Reference
{
i = 2; // Working on reference.
}
static void Main(string[] args)
{
int i = 1;
ProgramInt.Test(ref i);
Console.WriteLine(i);
Console.Read();
// Output: 2
}
}
Now I'm perplex as to why array members when passed in functions are implicitly passed by reference. Aren't arrays value types?
class ProgramIntArray
{
public static void Test(int[] ia) // Pass by Value
{
ia[0] = 2; // Working as reference?
}
static void Main(string[] args)
{
int[] test = new int[] { 1 };
ProgramIntArray.Test(test);
Console.WriteLine(test[0]);
Console.Read();
// Output: 2
}
}