Middle
Is it possible to pass significant data types by reference?
sobes.tech AI
Answer from AI
Yes, it is possible using the ref or in keywords.
Example with ref (for read and write):
void ModifyValue(ref int number)
{
number = number * 2;
}
// Usage
int myNumber = 10;
ModifyValue(ref myNumber); // myNumber is now 20
Example with in (read-only, for performance optimization when passing large structs):
void ReadValue(in MyStruct data)
{
Console.WriteLine(data.Value);
// data.Value = 10; // Compilation error, in makes the parameter readonly
}
struct MyStruct
{
public int Value;
}
// Usage
MyStruct myStruct = new MyStruct { Value = 5 };
ReadValue(in myStruct);
Example with out (for initialization inside the method):
void CreateValue(out int result)
{
result = 100;
// Console.WriteLine(result); // Compilation error, can be used only after assignment
}
// Usage
int outputValue;
CreateValue(out outputValue); // outputValue is now 100