Testing the effects of passing array references by value and by reference. : Ref Out « Language Basics « C# / C Sharp






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

 


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 };
   } 
}


        








Related examples in the same category

1.Reference, output and value parameters.
2.the out descriptor allows a function a value in an argument without initializing the argumentthe out descriptor allows a function a value in an argument without initializing the argument
3.compare the difference between passing a null reference vs. a reference to a zero length string