logo search
CSharp_Prog_Guide

Пример. Передача ссылочных типов по значению

В следующем примере демонстрируется передача параметра ссылочного типа arr по значению в метод Change. Поскольку этот параметр является ссылкой на arr, можно изменить значения элементов массива. Однако попытка назначить параметр другому адресу в памяти может быть выполнена только внутри метода и не влияет на исходную переменную arr.

------

Output

Inside Main, before calling the method, the first element is: 1

Inside the method, the first element is: -3

Inside Main, after calling the method, the first element is: 888

Code Discussion

In the preceding example, the array, arr, which is a reference type, is passed to the method without the ref parameter. In such a case, a copy of the reference, which points to arr, is passed to the method. The output shows that it is possible for the method to change the contents of an array element, in this case from 1 to 888. However, allocating a new portion of memory by using the new operator inside the Change method makes the variable pArray reference a new array. Thus, any changes after that will not affect the original array, arr, which is created inside Main. In fact, two arrays are created in this example, one inside Main and one inside the Change method.