Variable by val:
static void Main(string[] args)
{
int i = 3;
method1(i);
Console.WriteLine(i);
Console.ReadLine();
}
static void method1(int z)
{
z *= 2;
}
The output is 3 because method1 didn't change the variable in Main.
Variable by ref:
static void Main(string[] args)
{
int i = 3;
method1(ref i);
Console.WriteLine(i);
Console.ReadLine();
}
static void method1(ref int z)
{
z *= 2;
}
The output is 6 because method1 changed the variable in Main.
Array by val:
class Program
{
static void Main(string[] args)
{
int[] i = { 13, 1, 5 };
method1(i);
Console.WriteLine(String.Join(",",i));
Console.ReadLine();
}
static void method1(int[] z)
{
for(int m=0; m<z.Length;m++)
{
z[m] *= 2;
}
}
}
The output is 26, 2, 10.
Array by ref:
class Program
{
static void Main(string[] args)
{
int[] i = { 13, 1, 5 };
method1(ref i);
Console.WriteLine(String.Join(",",i));
Console.ReadLine();
}
static void method1(ref int[] z)
{
for(int m=0; m<z.Length;m++)
{
z[m] *= 2;
}
}
}
The output is again 26, 2, 10.
Conclusions: Variables can be passed either by value or by ref, in contrary to arrays that can be passed only by reference. Is it correct? If not - what is the difference between method1(ref int[] z) and method1(int[] z)? When are we expected to get different results?