Passing a constant array to a function in VB.NET

I know that you can easily pass an array to a function, for example, the code below shows

Private Sub SomeFunction(ByVal PassedArray() As String) For i As Integer = 0 To PassedArray.Count - 1 Debug.WriteLine(PassedArray(i)) Next End Sub Public Sub Test() Dim MyArray As String() = {"some", "array", "members"} SomeFunction(MyArray) End Sub 

But is there a way to pass a constant array of functions to VB.NET?

For example, in PHP you can write:

 function SomeFunction($array) { for($i=0;$i<count($array);$i++) { echo($array[$i]); } } function Test() { SomeFunction(array("some", "array", "members")); // Works for PHP } 

So, to repeat: is there a way to pass a constant array directly to functions in VB.NET? Is there any benefit to this? I guess a few bytes of memory could be saved.

PS :.

 SomeFunction({"some", "array", "member"}) ' This obviously gives a syntax error 
+4
source share
4 answers

Another thing that I just thought about does not directly answer the question, but perhaps it falls into the intent of the poster - the ParamArray keyword. If you control the function you call, it can make life a lot easier.

 Public Function MyFunction(ByVal ParamArray p as String()) ' p is a normal array in here End Function ' This is a valid call MyFunction(New String() {"a", "b", "c", "d"}) ' So is this MyFunction("a", "b", "c", "d") 
+2
source

Closest you can do the following:

 SomeFunction(New String() {"some", "array", "members"}) 

This is virtually identical in terms of objects created for what you placed. In fact, in .NET there are no array literals, but only initialization assistants.

+2
source
 SomeFunction({"some", "array", "member"}) ' this obviously gives a syntax error 

This is a perfectly valid syntax starting with VB10 (Visual Studio 2010). See this:

+2
source

No; there is no such thing as a constant array in the CLI; arrays are always mutable. Perhaps a ReadOnlyCollection<T> is appropriate?

In C # (supposedly similar in VB) you can do something like:

 private readonly static ReadOnlyCollection<string> fixedStrings = new ReadOnlyCollection<string>( new string[] { "apple", "banana", "tomato", "orange" }); 

Which gives you a static (= shared), non-editable, reusable collection. This works especially well if the method accepts IList<T> , IEnumerable<T> , etc. (Not an array, T[] ).

+1
source

All Articles