0

Say I create declare an array:

byte[] Data = new byte[4];

And I play around with the array, fill it with some values, etc. Later on in the code, if I say:

Data = new byte[16];

What am I doing: am I completley getting rid of the old array and creating a new empty one with 16 indexes? Or am I keeping the same array as before, but just extending the total number of indexes?

1
  • Array.Resize(Data, Data.Length + 12)? this will create a new array with 16 elements and retain the old 4 Commented Mar 26, 2014 at 17:53

4 Answers 4

4

What am I doing: am I completley getting rid of the old array and creating a new empty one with 16 indexes?

Yes. The old array will eventually get garbage collected and just "go away" (provided nothing else references it). Your new array will not retain any of the original values.

Or am I keeping the same array as before, but just extending the total number of indexes?

You are not. If you want this behavior, consider using List<byte> instead, which works very similarly to an array, but will grow as needed.

You can also use Array.Resize(Data, 16) to "resize" the array. Internally, this will create a new array, then copy the values from the old array to the new array, so the result will have a length of 16, but still retain the original 4 values.

Sign up to request clarification or add additional context in comments.

Comments

1

You are not growing the existing array. Data is a reference, what's happening is you're assigning that reference to a new block of memory (the byte[16] that is allocated) and, assuming there is no other reference which is equal to Data you are orphaning the memory you previously allocated which will result in it being garbage collected. If say, you did;

var Data = new byte[4];
var Data1 = Data;
Data = new byte[16];

Then the original four bytes of memory would not be queued for garbage collection until Data1 goes out of scope since you still have a reference to that memory.

Comments

0

You are creating a new array and setting it to the reference of your old array.

Once all references are gone from an object, the garbage collector picks it up and deletes it from memory.

Comments

0

When you create an array, in that situation Array class object has been created internally.

byte[] Data = new byte[4];

in this line Data is just an reference variable which is pointing to a memory.

Data = new byte[16];

when you execute this statement, it means you have created new array and pass its reference to the Data reference variable. now its lost the old array and pointing out to the new array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.