VB.NET Empty String Array

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

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

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

    You don't have to include String twice, and you don't have to use New.
    Either of the following will work...

    Dim strings() as String = {}
    Dim strings as String() = {}
    
    0 讨论(0)
  • 2021-01-07 18:40

    A little verbose, but self documenting...

    Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray
    
    0 讨论(0)
  • 2021-01-07 18:42

    Another way of doing this:

    Dim strings() As String = {}
    

    Testing that it is an empty string array:

    MessageBox.Show("count: " + strings.Count.ToString)
    

    Will show a message box saying "count: 0".

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

    The array you created by Dim s(0) As String IS NOT EMPTY

    In VB.Net, the subscript you use in the array is index of the last element. VB.Net by default starts indexing at 0, so you have an array that already has one element.

    You should instead try using System.Collections.Specialized.StringCollection or (even better) System.Collections.Generic.List(Of String). They amount to pretty much the same thing as an array of string, except they're loads better for adding and removing items. And let's be honest: you'll rarely create an empty string array without wanting to add at least one element to it.

    If you really want an empty string array, declare it like this:

    Dim s As String()
    

    or

    Dim t() As String
    
    0 讨论(0)
提交回复
热议问题