Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 533
Jorge Branco Avatar asked Jun 08 '09 22:06

Jorge Branco


People also ask

Are arrays automatically passed by reference in C?

The truth is, many books get this wrong as well; the array is not "passed" at all, either "by pointer" or "by reference". In fact, because arrays cannot be passed by value due to an old C restriction, there is some special magic that happens with arrays as function arguments.

Is array pass by reference or value in C?

Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array. The ampersand used in the function prototype. To make a normal parameter into a pass by reference parameter, we use the "& param" notation.

Are arrays being passed by reference?

Like all Java objects, arrays are passed by value ... but the value is the reference to the array. Real passing by reference involves passing the address of a variable so that the variable can be updated. This is NOT what happens when you pass an array in Java.

Are arrays always call by reference?

Since an array is passed as a pointer, the array's memory is not copied. The function uses the memory of the same array that is passed to it, and can change what is in that memory. Because arrays are already pointers, there is usually no reason to pass an array explicitly by reference.


2 Answers

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.

like image 54
Marc Gravell Avatar answered Oct 07 '22 08:10

Marc Gravell


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.

like image 39
plinth Avatar answered Oct 07 '22 07:10

plinth