C# Programming/Keywords/ref

From Wikibooks, open books for an open world
Jump to: navigation, search


The ref keyword explicitely 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
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach
goto if implicit in int
interface internal is lock long
namespace new null object operator
out override params private protected
public readonly ref return sbyte
sealed short sizeof stackalloc
static string struct switch this
throw true try typeof uint
ulong unchecked unsafe ushort using
var virtual void volatile while
Special C# Identifiers
add alias get global partial
remove set value where yield