VB.Net Initializing an array on the fly

I wrote this - a very simple function, and then I wondered if VB has some built-in functions for this, but could not find anything specific.

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

Not much to use as

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

Because it 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?

+5
arrays
source share
5 answers

Any reasons not to do:

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

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

I just checked and VB 9 implicitly printed arrays :

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

(This does not work in VB 8, as far as I know, but an explicit version. An implicit version is needed for anonymous types, which are also new to VB 9.)

+15
source share
 Dim somenames() As String = {"hello", "world"} 
+6
source share

The following codes will work in VB 10:

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

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

+2
source share
 PrintNames(New String(){"Hans", "Luke", "Lia"}) 
+1
source share

Microsoft recommends the following format

 Dim mixedTypes As Object() = New Object() {item1, item2, itemn} 

per http://msdn.microsoft.com/en-US/library/8k8021te(v=VS.80).aspx

Please note: you do not need to specify the size of the new array, as this is inferred from the initialized argument count. If you want to specify the length, you do not specify the "length", but the index number of the last space in the array. i.e. New Object (2) {0, 1, 2} 'argument 3 argument.

+1
source share

All Articles