Pass a parameter by reference.
|
var i = 10;
Method0(i);
Method1(ref i);
void Method0(int i) => i++;
void Method1(ref int i) => i++;
var item = new Item("init name");
Method2(item);
Method3(ref item);
void Method2(Item item) => item = new("new name 2");
void Method3(ref Item item) => item = new("new name 3");
|
Pass a parameter by reference and make it readonly.
Useful when you have a big value type and you want to pass only its reference for performances reason, but you don't want it to be overwritten.
|
var bigStruct = new BigStruct("name");
Method(ref bigStruct);
void Method(ref readonly BigStruct bigStruct)
{
bigStruct = new BigStruct("new name");
bigStruct.Name = "new name";
}
int[] array = [ 1, 2, 3, 4 ];
var bigStruct = new BigStruct(array);
ref readonly int element = ref bigStruct.GetElement(2);
element = 5;
ref readonly int GetElement(int index) => ref data[index];
|
 |
If the variable is a readonly variable, you must use the in modifier while calling the method. |
Create a temporary variable for the argument and pass the argument by readonly reference.
|
var i = 10;
Method(in i);
void Method6(in int i)
{
i = 5;
}
|
Allow to initialize the parameter in the method.
|
Method5(out var j);
void Method5(out int i) => i = 5;
|
|
Method(1, 2, 3);
void Method(params int[] integers)
{ }
|