C# Programming/Keywords/ref
The ref
keyword explicitly specifies that a variable should be passed by reference rather than by value.
A developer may wish to pass a variable by reference particularly in case of value types. If a variable is passed by reference, only a pointer is sent to a function in reality, reducing the cost of a method call in case it would involve copying large amounts of data, something C# does when normally passing value types.
Another common reason to pass a variable by reference is to let the called method modify its value. Because this is allowed, C# always enforces specifying that a value is passed by reference even in the method call, something many other programming languages don't. This let developers reading the code easily spot places that can imply a type has had its value changed in a method, which is useful when analyzing the program flow.
Passing a value by reference does not imply that the called method has to modify the value; see the out keyword for this.
Passing by reference requires the passed variable to be initialized.
An example of passing a variable by reference follows:
void CallingMethod()
{
int i = 24;
if (DoubleIfEven(ref i))
Console.WriteLine("i was doubled to {0}", i); // outputs "i was doubled to 48"
}
bool DoubleIfEven(ref int iValue)
{
if (iValue%2 == 0)
{
iValue *= 2;
return true;
}
return false;
}
C# Keywords | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Special C# Identifiers (Contextual Keywords) | |||||||||||||||
| |||||||||||||||
Contextual Keywords (Used in Queries) | |||||||||||||||
|