If you assign to a parameter of a method, for that assignment to be visible to the caller, the parameter must have the ref
(or out
) modifier. See ref (C# Reference).
Example:
// doesn't do anything!
void Copy(BaseObject target)
{
...
target = Something;
}
// with ref, assignment is to the *same* variable as the caller gave
void Copy(ref BaseObject target)
{
...
target = Something;
}
ADDITION:
As the link I provided notes:
Do not confuse the concept of passing by reference with the concept of reference types
These two concepts are "orthogonal", as the following table illustrates:
| |
| ByVal (neither | ByRef (ref or
| ref nor out): | out keyword):
| |
--------------------------------------------+-------------------+----------------------
value type (struct, enum) | entire object | no copy, argument
| is COPIED | must be a variable,
| | same variable used
--------------------------------------------+-------------------+----------------------
reference type (class, interface, delegate) | reference COPIED; | no copy, argument
| NEW reference to | must be a variable,
| same object | same variable used
--------------------------------------------+-------------------+----------------------
If you don't use mutable structs, then variables of struct type can only ever change through re-assignemnt, and then the following rule-of-thumb is useful for both value types and reference types:
You need the
ref
(orout
) keyword if and only if your method assigns (including compund assignment like+=
) to the parameter in question.
See also What is the use of “ref” for reference-type variables in C#?.