Reference Local Variables in C# 7
Starting from C# 7 version, the language has a feature that allows declaring a local variable that references an array element or a field in an object:
int[] simpleArray = {0, 1, 2, 3, 4, 5, 6, 7, 8};
ref int simpleElementRef = ref simpleArray[3];
simpleElementRef — reference to simpleArray[3]. Changing simpleElementRef leads to changing the array element:
simpleElementRef *= 15;
Console.WriteLine(simpleElementRef); // 15
Console.WriteLine(simpleArray[3]); // 15
A reference local variable can be declared with an array element, field, or a regular local variable as its target. The target cannot be a property.
Reference local variables are used for special micro-optimization scenarios and are typically used in combination with returned reference values.
Returned Reference Values
Reference local variables can be returned from methods. As a result, we get a returned reference value:
static string X = "Старое значение";
static ref string GetX() => ref X; // Возвращает ссылочное значение
static void Main()
{
ref string xRef = ref GetX(); // Присваивает результат ссылочной локальной переменной
xRef = "Новое значение";
Console.WriteLine(X); // Выводит Новое значение
}
That's it. :)
Comments (0)
No comments yet.