views:

22

answers:

2

the message was variable j is used before it have been assigned value.If in php language, it's not a problem at all.

Dim j() As String
        Dim i As Integer
        If (i = 1) Then
            j(0) = "x"
        Else
            j(0) = "d"
        End If
+1  A: 

in php language,it's not a problem at all.

php doesn't use real arrays. A real array is a contiguous block of memory. Php uses a collection type with array-like semantics that it just calls an array, and collections seldom make the same kind of guarantees about continuity because of performance problems caused when the collection grows at runtime.

If you want php-style "arrays" in .Net, you need to do the same thing php does and use a collection. The System.Collections.Generics.List<T> type works pretty well. Then you can append to the List by using its .Add() method or using the collection initializer syntax demonstrated below (requires Visual Studio 2010):

Dim i As Integer = 1
Dim j As New List(Of String) From { If(i = 1, "x","d") }

We can forgive php it's naming lapse, though, as real arrays should be used sparingly. A collection is almost always more appropriate.

Joel Coehoorn
i got the answer but the diffirent ways.Vb.net assign array as allocation.So if there were not allocation so cannot be parse.[pre][code] Dim m As Integer m = 9 Dim j(m) As String Dim i As Integer i = 1 If (i = 1) Then j(0) = "x" Else j(0) = "d" End If MsgBox(j(0))[/code][/pre>
hafizan
A: 

Arrays are reference types, reference types have to be created before they can be used. You are attempting to assign a value to the first element of the array j, without first creating the array. If it works in PHP that's because PHP is doing some auto-magical initialization (i.e. best guess).

Now, arrays in .Net are of a fixed size, determined when they are created. If you are dealing with an array that doesn't change size, then you could declare it as:

    Dim x As Integer = 100 ' or whatever is appropriate.
    Dim j() as String = New String(x)

    Dim i As Integer
        If (i = 1) Then
            j(0) = "x"
        Else
            j(0) = "d"
        End If

If you don't know the number of elements in advance, then you shouldn't use an array, you should use a list.

    Dim j as List(Of String) = New List(Of String)

    Dim i As Integer
        If (i = 1) Then
            j.Add("x")
        Else
            j.Add("d")
        End If

To use the List you'll have to import System.Collections.Generic. I'd really recommend using a list unless absolutely forced to do otherwise -- it's simply a much better structure to deal with.

jmoreno