C Sharp Programming/Keywords/ref

The 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 keyword for this.

Passing by reference requires the passed variable to be initialized.

An example of passing a variable by reference follows:

/Keywords