Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of memory semantics govern array assignment in c#?

Tags:

c#

.net

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?

like image 373
Dark Star1 Avatar asked Dec 07 '22 06:12

Dark Star1


1 Answers

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.

like image 192
JaredPar Avatar answered Feb 23 '23 01:02

JaredPar