views:

61

answers:

2

If I dim an array to say, 5 elements, should it not fail if I go to add a 6th? I thought this used to require a redim. In .NET 2.0, I have a character array of length = 3. When I populate it from the db, one record had 4 characters in it and it successfully added all 4 characters to the array?

+3  A: 

If you assign an array of characters to an existing array variable containing an array (of any size), it creates a new array of the size that is required. The original array is garbage collected.

char[] c = new char[3];
c = reader.ReadCharacters(5);  // read 5 characters into new array, assign to c
Debug.Print(c.Length);         // Prints 5. 
Robert Harvey
Seems odd that, after defining it as 5, separately, when reading from the db I have to specify only grab 5 characters.
donde
Think of the array variable as holding a reference to an array on the heap. When you assign a new array to the variable, the variable now holds a reference to the new array, not the old one.
Robert Harvey
+1  A: 

Just to add to the current answer, in case this was the problem. In VB.NET, you declare arrays with the upper bound, not the length desired.

For example:

Dim arr(3) as Integer  'length of 4

This array has 4 elements, 0 - 3. It does not have a length of 3 as would be the case if you said this in C#:

int[] arr = new int[3];  //length of 3

I don't know if this is your issue, but just in case.

Marc