I'm trying to do something with array passed to the function in .NET and I'm a little confused. Array is reference type so changes made to array passed to the function are visible outside the function. Example
static void Main(string[] args)
{
byte[] arr = new byte[] { 1,2, 3, 4, 5 };
Console.WriteLine(string.Join("", arr)); //console output: 12345
doSomething(arr);
Console.WriteLine(string.Join("", arr)); //console output: 52341
}
static void doSomething(byte[] array)
{
byte tmp = array[0];
array[0] = array[array.Length - 1];
array[array.Length - 1] = tmp;
}
so it works exactly the same as with "ref" keyword used (same console output)
doSomething(ref arr); for static void doSomething(ref byte[] array)
However if I add following line to my function:
array = (new byte[] { 1 }).Concat(array).ToArray(); //size of array is changed
the results are different:
12345
52341// "ref" keyword is not used
and
12345
152341 "ref" keyword is used
Could someone explain me why results are different ?