Passing Arrays Using ref and out (C# Programming Guide)

Switch View :
ScriptFree
Visual Studio 2010 - Visual C#
Passing Arrays Using ref and out (C# Programming Guide)

Like all out parameters, an out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee. For example:

C#

static void TestMethod1(out int[] arr)
{
    arr = new int[10];   // definite assignment of arr
}


Like all ref parameters, a 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. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example:

C#

static void TestMethod2(ref int[] arr)
{
    arr = new int[10];   // arr initialized to a different array
}


The following two examples demonstrate the difference between out and ref when used in passing arrays to methods.

Example

In this example, the array theArray is declared in the caller (the Main method), and initialized in the FillArray method. Then, the array elements are returned to the caller and displayed.

C#

class TestOut
{
    static void FillArray(out int[] arr)
    {
        // Initialize the array:
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] theArray; // Initialization is not required

        // Pass the array to the callee using out:
        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] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1 2 3 4 5        
    */


In this example, the array theArray is initialized in the caller (the Main method), and passed to the FillArray method by using the ref parameter. Some of the array elements are updated in the FillArray method. Then, the array elements are returned to the caller and displayed.

C#

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] = 1111;
        arr[4] = 5555;
    }

    static void Main()
    {
        // Initialize the array:
        int[] theArray = { 1, 2, 3, 4, 5 };

        // 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] + " ");
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
    /* Output:
        Array elements are:
        1111 2 3 4 5555
    */


See Also

Reference

Concepts

Community Content

J Dunlap Jr
Example clarity
I thought that the difference between them in the documentation and examples was clear.  It is simply this:

An array that is passed using ref must be initialized in the caller and does not need to be assigned in the called function.
An array that is passed using out does not need to be initialized in the caller, but must be assigned in the called function.

Other than those differences, they are pretty much the same.

Peter Simard
Enter title here.Inproper Examples

I think the problemn here is with the examples and what purpose they are trying to achieve. I would also be confused if I read the topics that went over passing by ref/out and then trying to make sense of the purpose of the examples. The topic title is 
    "Passing Arrays Using ref and out (C# Programming Guide)"

This gives you the initial perception that there is a difference between passing an array via a ref or out. The problem is that the examples do not in any way clarify what that difference is.  So the inital comment is correct based on what is being demonstrated and how it is documented. A clarification of the passing the argument via ref/out should have been made. This is amlost akin to the concept of passing a pointer to a pointer in the C/C++ world.

Microsoft is not good at documentation and you should always pay close attention to what is being documented and always use the reference doc section to get quick access to the secondary topics in the topic being viewed.


Roketh
ref ?
RE:  S.P.G.   I think you miss read the OP's question.  His question was simply why would one pass an array by ref, when it is already done so by default. However Damian is also correct in that you cannot change the array itself without using ref.  But you can change its contents without ref.

DamianF
The point of using ref or out
The answer is that, without ref or out, the array variable itself cannot be changed.  When the caller gets it back, it will always be the same Array object that it was before the call.  With ref or out, the called function can alter the actual contents of the passed variable, e.g. by nulling it out or replacing it with an array of a different size. $0$0 $0 $0Damian$0 $0$0 $0

S.P.G
ref ?
I don't think you understand programming.

Passing a ref type by ref and passing it by val is not the same thing, they are very different.

I won't explain, get back to me in a few years.


ademasson
ref ?
I don't see any advantage in using ref with method parameters of the array type as array types are reference types : same results if ommitting ref in the method body and method call