views:

405

answers:

5

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

A: 

Yes, they are passed by reference by default in C#. All objects in C# are, except for value types. To be a little bit more precise, they're passed "by reference by value"; that is, the value of the variable that you see in your methods is a reference to the original object passed. This is a small semantic point, but one that can sometimes be important.

McWafflestix
The reference is passed by value; which is very different to "they are passed by reference".
Marc Gravell
A: 

They are passed by value (as are all parameters that are neither ref nor out), but the value is a reference to the object, so they are effectively passed by reference.

plinth
+8  A: 

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 chanegs 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.

Marc Gravell
+2  A: 

Here's Jon Skeet's article on parameter passing in C#. He says it better than I can.

Jason Punyon
A: 

An array is a reference. And it is passed by value.

Ray