Skip to content

Latest commit

 

History

History
43 lines (34 loc) · 2.84 KB

File metadata and controls

43 lines (34 loc) · 2.84 KB
title Passing Arrays Using ref and out (C# Programming Guide)
ms.date 07/20/2015
ms.prod .net
ms.technology
devlang-csharp
ms.topic article
helpviewer_keywords
arrays [C#], passing using ref and out
ms.assetid 6a2b261e-a1cc-49a6-b4f0-6cacae385a1e
caps.latest.revision 16
author BillWagner
ms.author wiwagn

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:

[!code-csharpcsProgGuideArrays#39]

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:

[!code-csharpcsProgGuideArrays#40]

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.

[!code-csharpcsProgGuideArrays#37]

Example

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.

[!code-csharpcsProgGuideArrays#38]

See Also

ref
out parameter modifier
C# Programming Guide
Arrays
Single-Dimensional Arrays
Multidimensional Arrays
Jagged Arrays