VB.NET Empty String Array

后端 未结 10 843
花落未央
花落未央 2021-01-07 17:56

How can I create an empty one-dimensional string array?

相关标签:
10条回答
  • 2021-01-07 18:19

    try this Dim Arraystr() as String ={}

    0 讨论(0)
  • 2021-01-07 18:24

    Dim array As String() = Array.Empty(Of String)

    0 讨论(0)
  • 2021-01-07 18:27

    VB is 0-indexed in array declarations, so seomthing like Dim myArray(10) as String gives you 11 elements. It's a common mistake when translating from C languages.

    So, for an empty array, either of the following would work:

    Dim str(-1) as String ' -1 + 1 = 0, so this has 0 elements
    Dim str() as String = New String() { } ' implicit size, initialized to empty
    
    0 讨论(0)
  • 2021-01-07 18:29

    Not sure why you'd want to, but the C# way would be

    string[] newArray = new string[0];
    

    I'm guessing that VB won't be too dissimilar to this.

    If you're building an empty array so you can populate it with values later, you really should consider using

    List<string>
    

    and converting it to an array (if you really need it as an array) with

    newListOfString.ToArray();
    
    0 讨论(0)
  • 2021-01-07 18:35

    Dim strEmpty(-1) As String

    0 讨论(0)
  • 2021-01-07 18:36

    Something like:

    Dim myArray(9) as String
    

    Would give you an array of 10 String references (each pointing to Nothing).

    If you're not sure of the size at declaration time, you can declare a String array like this:

    Dim myArray() as String
    

    And then you can point it at a properly-sized array of Strings later:

    ReDim myArray(9) as String
    

    ZombieSheep is right about using a List if you don't know the total size and you need to dynamically populate it. In VB.NET that would be:

    Dim myList as New List(Of String)
    myList.Add("foo")
    myList.Add("bar")
    

    And then to get an array from that List:

    myList.ToArray()
    

    @Mark

    Thanks for the correction.

    0 讨论(0)
提交回复
热议问题