0

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

On my machine a pointer is 32 bits, therefore a function that passes a class object will be passing 32 bits (the pointer that is the reference to the class object). I keep hearing contradictory things about arrays in c sharp, that they are reference types, and that they are passed by value. So could someone please tell me how many bits a function that passes an array of 5 floats will use in passing that array? Is it the size of a pointer, or 5 * 32 the size of 5 floats?

Community
  • 1
  • 1
ste3e
  • 995
  • 1
  • 9
  • 18
  • http://stackoverflow.com/questions/967402/are-arrays-or-lists-passed-by-default-by-reference-in-c , http://stackoverflow.com/questions/11977988/why-are-objects-passed-by-value-modified-as-if-they-are-passed-by-reference , http://stackoverflow.com/questions/4617306/c-sharp-constructor-object-parameter-is-passed-by-reference-or-value , http://stackoverflow.com/questions/967402/are-arrays-or-lists-passed-by-default-by-reference-in-c (etc -- can you vote to close your *own* question as a duplicate? Because, if so, pick something ..) –  Sep 19 '12 at 04:19

3 Answers3

2

Arrays are reference types and thus it only passes the reference, not all the values.

Passing Arrays as Arguments (C# Programming Guide)

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements

You may see this article by Jon Skeet: Parameter passing in C#

Habib
  • 219,104
  • 29
  • 407
  • 436
  • But the [possibly] confusing thing is that the "reference" is passed by value .. (So it's "Call by Value [of the Reference]" or more simply "Call by Object Sharing") –  Sep 19 '12 at 04:17
  • @pst, reference is always passed by value, isn't it ? – Habib Sep 19 '12 at 04:18
  • I never said it was not. However, it is confused often with "Call by Reference", silly overloaded terms, and thus leads to confusion if it's not *explicitly clarified* said (e.g. "[array] passed by value"), because it's the value of the .. and on it goes. –  Sep 19 '12 at 04:21
1

All arrays are reference types:

To quote MSDN:

Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable, you can use foreach iteration on all arrays in C#.

So passing an array to a function passes a reference, which will be the same size no matter how many elements are in the array. In you example that would be 32 bits.

shf301
  • 31,086
  • 2
  • 52
  • 86
1

Array is reference type and each reference is 4 bytes (on a 32-bit system) or 8 bytes (on a 64-bit system) large. That for reference, for the size just multiply its length with the reference size and add the class definition overhead (few bytes for variables and few for memory management).

Erre Efe
  • 15,387
  • 10
  • 45
  • 77