Are arrays or lists passed by default by reference in c#?

Jorge Branco picture Jorge Branco · Jun 9, 2009 · Viewed 51.7k times · Source

Do they? Or to speed up my program should I pass them by reference?

Answer

Marc Gravell picture Marc Gravell · Jun 9, 2009

The reference is passed by value.

Arrays in .NET are object on the heap, so you have a reference. That reference is passed by value, meaning that changes to the contents of the array will be seen by the caller, but reassigning the array won't:

void Foo(int[] data) {
    data[0] = 1; // caller sees this
}
void Bar(int[] data) {
    data = new int[20]; // but not this
}

If you add the ref modifier, the reference is passed by reference - and the caller would see either change above.