Vb.net – Different ways of declaring arrays in VB.NET

arraysvb.net

In VB.NET, is there any difference between the following ways of declaring arrays?

- Dim cargoWeights(10) as Double

- cargoWeights = New Double(10) {}

' These are two independent statements. They are not supposed to execute one after the other.

As far as I know, the first one just declares an array variable that holds the value 'Nothing' until some array object is assigned to it. In other words, it is not initialized yet.

But what about the second statement? Does the "=" sign means the variable is already being initialized and won't hold 'Nothing'? Is it going to point to an one-dimensional array of eleven default Double values (0.0)?

EDIT:

According to MSDN website:

The following example declares an array variable that does not initially point to any array.

Dim twoDimStrings( , ) As String

(…) the variable twoDimStrings has the value Nothing.

Source: http://msdn.microsoft.com/en-us/library/18e9wyy0(v=vs.80).aspx

Best Answer

Both Dim cargoWeights(10) as Double and cargoWeights = New Double(10) {} will actually initialize an array of doubles with each items set to default type value, which in this case, 0.0. (Or Nothing if String data type)

The difference between the two syntax is that, the 2nd one you can init the value of each items in the array to different from default value, like:

cargoWeights = New Double(10) {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

To declare uninitialized array, use Dim cargoWeights() As Double or cargoWeights = New Double() {}.