HOW TO PASS ARRAYS USING REF AND OUT PARAMETER

Anupam Mishra

Total Post:135

Points:949
Posted by  Anupam Mishra
C#  ASP.Net 
C#
 586  View(s)
Ratings:
Rate this:
Hi Everyone,
I am working on arrays and i need to pass arrays using ref and out parameter in a function.my function are given below:
static void FillArray(ref int[] arr)
{
.......
}
Please can anyone give me a solution in both cases(ref and out parameter).
  1. Manoj Bhatt

    Post:154

    Points:1086
    Re: How to pass arrays using ref and out parameter

    ref parameter:  ref parameter of an array type must be definitely assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. 

    out parameter:  An out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee.
    Here we demonstrate using your method for both cases:
    
    

      // For out parameter

        class TestOut

        {

            static void FillArray(out int[] arr)

            {

                // Initialize the array:

                arr = new int[5] { 10,20,30,40,50 };

            }

           public static void MainE()

            {

                // Initialization is not required

                int[] theArray;

                // Pass the array to the callee using out parameter:

                FillArray(out theArray);

                // Display the array elements:

                System.Console.WriteLine("Array elements are:");

                for (int i = 0; i < theArray.Length; i++)

                {

                    System.Console.Write(theArray[i] +" ");

                }

               }

        }

        // For Ref Parameter

        class TestRef

        {

            static void FillArray(ref int[] arr)

            {

                // Create the array on demand:

                if (arr == null)

                {

                    arr = new int[10];

                }

                // Fill the array:

                arr[0] = 1000;

                arr[4] = 5000;

            }

            static void Main()

            {

                // Calling Out parameter static method

                TestOut.MainE();

                // Initialize the array:

                int[] theArray = { 10,20,30,40,50 };

                // Pass the array using ref:           

                FillArray(ref theArray);

                // Display the updated array:

                System.Console.WriteLine("Array elements are:");

                for (int i = 0; i < theArray.Length; i++)

                {

                    System.Console.Write(theArray[i] +" ");

                }          

                System.Console.ReadKey();

            }

        }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!