logo
CSharp_Prog_Guide

Рассмотрение кода

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

Example: Passing Reference Types by Reference

This example is the same as the previous example, except for using the ref keyword in the method header and call. Any changes that take place in the method will affect the original variables in the calling program.

class PassingRefByRef

{

static void Change(ref int[] pArray)

{

// Both of the following changes will affect the original variables:

pArray[0] = 888;

pArray = new int[5] {-3, -1, -2, -3, -4};

System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);

}

static void Main()

{

int[] arr = {1, 4, 5};

System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);

Change(ref arr);

System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);

}

}

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: -3

Code Discussion

All of the changes that take place inside the method affect the original array in Main. In fact, the original array is reallocated using the new operator. Thus, after calling the Change method, any reference to arr points to the five-element array, which is created in the Change method.