tags:

views:

102

answers:

5

Given the following: byte[] sData; and a function declared as private byte[] construct_command()

if I were to then assign the result of construct_command() to sData would sData just point to the contents of what's returned from the function or would some space be alloctaed for sData in memory and the contents of the result of the function be copied into it?

+2  A: 

sData will point to the contents of what's returned from the function. Arrays in C# are reference types, which means that assigning one array from another simply copies the reference rather than allocating new data.

JSBangs
+1  A: 

Assuming sData is a local variable, it will live in the stack and it will refer to the array returned by the method. The method does not return the contents of the array itself, but a reference to the array.

In .net, arrays are first class objects and all array-type variables are in fact references.

Rui Craveiro
+4  A: 

The assignment will simply assign the sData to reference the instance returned by construct_command. No copying of data will occur.

In general, the CLR breaks the world down into 2 types

  • Value Types: This is anything that derives from System.ValueType. Assignment between values of these types happens by value and essentially results in a copy of the values between locations
  • Reference Types: Anything else. Assignment between values of these types simply causes the location to reference a different object in memory. No copying of values occurs

Arrays are reference types in the CLR and hence do not cause a copying of the underlying value.

JaredPar
So does this mean there's danger of the contents being destroyed before the method which contains the local variable (sData) returns?
Dark Star1
No, because the garbage collector will know that the array is still referenced.
Jon Skeet
A: 

sData would point to the array returned by construct_command.

sepp2k
+2  A: 

Array is a reference type hence only reference is copied. There is No content manipulation.

Dewfy