Home > DeveloperSection > Forums > How to pass arrays using ref and out parameter
Anupam Mishra

Total Post:135

Points:949
Posted on    February-09-2016 11:25 PM

 C# C#  ASP.Net 
Ratings:


 1 Reply(s)
 306  View(s)
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).


Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    February-09-2016 11:49 PM

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();

        }

    }


Don't want to miss updates? Please click the below button!

Follow MindStick