logo search
CSharp_Prog_Guide

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

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

Example: Swapping Two Strings

Swapping strings is a good example of passing reference-type parameters by reference. In the example, two strings, str1 and str2, are initialized in Main and passed to the SwapStrings method as parameters modified by the ref keyword. The two strings are swapped inside the method and inside Main as well.

class SwappingStrings

{

static void SwapStrings(ref string s1, ref string s2)

// The string parameter is passed by reference.

// Any changes on parameters will affect the original variables.

{

string temp = s1;

s1 = s2;

s2 = temp;

System.Console.WriteLine("Inside the method: {0} {1}", s1, s2);

}

static void Main()

{

string str1 = "John";

string str2 = "Smith";

System.Console.WriteLine("Inside Main, before swapping: {0} {1}", str1, str2);

SwapStrings(ref str1, ref str2); // Passing strings by reference

System.Console.WriteLine("Inside Main, after swapping: {0} {1}", str1, str2);

}

}

Output

Inside Main, before swapping: John Smith

Inside the method: Smith John

Inside Main, after swapping: Smith John

Code Discussion

In this example, the parameters need to be passed by reference to affect the variables in the calling program. If you remove the ref keyword from both the method header and the method call, no changes will take place in the calling program.