Passing arrays and array elements to methods in C#

using System;
 
public class ArrayPassingToMethods
{
 
   public static void Main( string[] args )
   {
      int[] array = { 1, 2, 3, 4, 5 };
 
     foreach ( int value in array )
         Console.Write( "   {0}", value );
 
      ModifyArray( array ); // pass array reference
      Console.WriteLine( "\n\nThe values of the modified array are:" );
 
      foreach ( int value in array )
         Console.Write( "   {0}", value );
 
      Console.WriteLine("array[3] before ModifyElement: {0}", array[ 3 ] );
 
      ModifyElement(array[ 3 ]); 
      Console.WriteLine(
         "array[3] after ModifyElement: {0}", array[ 3 ] );
   } // end Main
 
   // change each element of an array by 2 
   public static void ModifyArray( int[] array2 )
   {
      for ( int counter = 0; counter < array2.Length; counter++ )
         array2[ counter ] *= 2;
   } // end method ModifyArray
 
   // double argument by 2
   public static void ModifyElement( int element )
   {
      element *= 2;
      Console.WriteLine(
         "Value of element in ModifyElement: {0}", element );
   }
} // end class ArrayPassingToMethods

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.