Testing the effects of passing array references by value and by reference.

image_pdfimage_print

using System;

public class ArrayReferenceTest
{
public static void Main( string[] args )
{
int[] firstArray = { 1, 2, 3 };
int[] firstArrayCopy = firstArray;
for ( int i = 0; i < firstArray.Length; i++ ) Console.Write( "{0} ", firstArray[ i ] ); FirstDouble( firstArray ); for ( int i = 0; i < firstArray.Length; i++ ) Console.Write( "{0} ", firstArray[ i ] ); if ( firstArray == firstArrayCopy ) Console.WriteLine("same" ); else Console.WriteLine("different" ); int[] secondArray = { 1, 2, 3 }; int[] secondArrayCopy = secondArray; for ( int i = 0; i < secondArray.Length; i++ ) Console.Write( "{0} ", secondArray[ i ] ); SecondDouble( ref secondArray ); for ( int i = 0; i < secondArray.Length; i++ ) Console.Write( "{0} ", secondArray[ i ] ); if ( secondArray == secondArrayCopy ) Console.WriteLine("same" ); else Console.WriteLine("different" ); } public static void FirstDouble( int[] array ) { for ( int i = 0; i < array.Length; i++ ) array[ i ] *= 2; array = new int[] { 11, 12, 13 }; } public static void SecondDouble( ref int[] array ) { for ( int i = 0; i < array.Length; i++ ) array[ i ] *= 2; array = new int[] { 11, 12, 13 }; } } [/csharp]