60

I am looking for the VB.NET equivalent of

var strings = new string[] {"abc", "def", "ghi"};
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
erik
  • 6,406
  • 3
  • 36
  • 36

6 Answers6

82
Dim strings() As String = {"abc", "def", "ghi"}
Ben McCormack
  • 32,086
  • 48
  • 148
  • 223
gfrizzle
  • 12,419
  • 19
  • 78
  • 104
  • Not too sure I like the array indicator on the variable name, it goes against common convention. Especially in other languages. – ganjeii Apr 18 '19 at 20:58
  • @ganjeii Not all languages: C for example, but also and more importantly in this case VBA, only accept this syntax for array declaration – joH1 Sep 06 '19 at 12:28
  • Note that as inferred in the next answer these two are equivalent: `Dim strings() As String` `Dim strings As String()` – Shaggie Apr 20 '21 at 20:42
46

There are plenty of correct answers to this already now, but here's a "teach a guy to fish" version.

First create a tiny console app in C#:

class Test
{
    static void Main()
    {
        var strings = new string[] {"abc", "def", "ghi"};
    }
}

Compile it, keeping debug information:

csc /debug+ Test.cs

Run Reflector on it, and open up the Main method - then decompile to VB. You end up with:

Private Shared Sub Main()
    Dim strings As String() = New String() { "abc", "def", "ghi" }
End Sub

So we got to the same answer, but without actually knowing VB. That won't always work, and there are plenty of other conversion tools out there, but it's a good start. Definitely worth trying as a first port of call.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 10
    I agree that Reflector should be in every .NET developers tool belt. But for this it would be simpler to use the online converter at http://converter.telerik.com/ – Jesper Palm Aug 20 '10 at 18:36
  • This is good for specifying that `{Nothing}` is an array of `String` or basically any other type, as opposed an array of `Object`, which a compiler will assume in *certain particular scenarios* if you don't include `New String() ` before the contents. – Panzercrisis Jun 09 '17 at 12:39
10

In newer versions of VB.NET that support type inferring, this shorter version also works:

Dim strings = {"abc", "def", "ghi"}
Netricity
  • 2,550
  • 1
  • 22
  • 28
6
Dim strings As String() = New String() {"abc", "def", "ghi"}
David Mohundro
  • 11,922
  • 5
  • 40
  • 44
  • 5
    Ah, but this did help me pass in an inline declaration to a function: MyFunction(somestring, New String() {"abc", "def", "ghi"}) – Ben McIntyre Mar 14 '12 at 01:47
5

Not a VB guy. But maybe something like this?

Dim strings = New String() {"abc", "def", "ghi"}

(About 25 seconds late...)

Tip: http://www.developerfusion.com/tools/convert/csharp-to-vb/

Jesper Palm
  • 7,170
  • 31
  • 36
4

Dim strings As String() = {"abc", "def", "ghi"}

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
Steve Wright
  • 2,481
  • 3
  • 26
  • 35