Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a constant array to a function in VB.NET

I know that you can easily pass an array to a function, like 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 to a function in VB.NET?

For instance in PHP, you could 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 reiterate: Is there a way to pass a constant array directly to a function in VB.NET? Is there any benefit in doing so? I imagine a few bytes of memory could be spared.

PS.:

SomeFunction({"some", "array", "member"}) ' This obviously gives a syntax error
like image 867
Gert Avatar asked Jul 23 '09 13:07

Gert


People also ask

How do you pass a constant array to a function?

To pass constant arrays to functions:In functionpassconstarrays. m, enter the code shown in Listing 4.15. This code creates an array and passes it to a function named adder() whose prototype indicates that it takes constant arrays.

Can you pass an array through a function?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.


2 Answers

The closest you can do is:

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

This is actually identical in terms of objects created to what you posted. There aren't actually array literals in .NET, just helpers for initialization.

like image 148
Ryan Brunner Avatar answered Sep 21 '22 00:09

Ryan Brunner


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

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

  • New Features in Visual Basic 10, under Array Literals.
like image 28
Neolisk Avatar answered Sep 18 '22 00:09

Neolisk