Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

method is possible with ref but not with out:

public void EmtyRef(bool condition, ref int value)

{

if (condition)

{

value += 10;

}

}

public void EmtyOut(bool condition, out int value)

{

if (condition)

{

value = 10;

}

} //CS0177: The out parameter 'value' must be assigned before control leaves the current method

This is because if condition does not hold, value goes unassigned.

Section 31.6: Passing by reference

If you want the Value Types vs Reference Types in methods example to work properly, use the ref keyword in your method signature for the parameter you want to pass by reference, as well as when you call the method.

public static void Main(string[] args)

{

...

DoubleNumber(ref number); // calling code Console.WriteLine(number); // outputs 8

...

}

public void DoubleNumber(ref int number)

{

number += number;

}

Making these changes would make the number update as expected, meaning the console output for number would be 8.

GoalKicker.com – C# Notes for Professionals

133