Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.Net Initialising an array on the fly

Tags:

arrays

vb.net

I wrote this - very simple - function, and then wondered does VB have some pre-built functionality to do this, but couldn't find anything specific.

Private Shared Function MakeArray(Of T)(ByVal ParamArray args() As T) As T()
    Return args
End Function

Not so much to be used like

Dim someNames() as string = MakeArray("Hans", "Luke", "Lia")

Because this can be done with

Dim someNames() as string = {"Hans", "Luke", "Lia"}

But more like

public sub PrintNames(names() as string)
   // print each name
End Sub

PrintNames(MakeArray("Hans", "Luke", "Lia"))

Any ideas?

like image 254
Binary Worrier Avatar asked Mar 12 '09 11:03

Binary Worrier


People also ask

How do you initialize an array in Visual Basic?

In visual basic, Arrays can be initialized by creating an instance of an array with New keyword. By using the New keyword, we can declare and initialize an array at the same time based on our requirements.

How do you declare an array of strings in VB?

String array. In the VB.NET language we can create the array with all its data in an initialization statement. Version 1 The first array is created with an initialization statement. We do not need to specify the size of the array on the left side. Version 2 The next array uses the longer syntax.

How do I declare an array in VB 6?

Declaring arraysArrays may be declared as Public (in a code module), module or local. Module arrays are declared in the general declarations using keyword Dim or Private. Local arrays are declared in a procedure using Dim or Static. Array must be declared explicitly with keyword "As".

What is static array in VB?

Static arrays must include a fixed number of items, and this number must be known at compile time so that the compiler can set aside the necessary amount of memory. You create a static array using a Dim statement with a constant argument:' This is a static array.


4 Answers

Any reason not to do:

Dim someNames() as string = New String(){"Han", "Luke", "Leia"}

The only difference is type inference, as far as I can tell.

I've just checked, and VB 9 has implicitly typed arrays too:

Dim someNames() as string = { "Han", "Luke", "Leia" }

(This wouldn't work in VB 8 as far as I know, but the explicit version would. The implicit version is necessary for anonymous types, which are also new to VB 9.)

like image 112
Jon Skeet Avatar answered Dec 02 '22 02:12

Jon Skeet


Dim somenames() As String = {"hello", "world"}
like image 38
mmx Avatar answered Dec 02 '22 01:12

mmx


The following codes will work in VB 10:

Dim someNames = {"Hans", "Luke", "Lia"} 

http://msdn.microsoft.com/en-us/library/ee336123.aspx

like image 42
T Jose Avatar answered Dec 02 '22 02:12

T Jose


PrintNames(New String(){"Hans", "Luke", "Lia"})
like image 32
Joe Avatar answered Dec 02 '22 02:12

Joe