Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Optional Array in as Parameter

Status
Not open for further replies.

onedizzydevil

Programmer
Mar 24, 2001
103
US
Need your help

I am trying to something like this, but I get an "Expression expect." squiggly

I the user to pass in an Arry list of items. Any help would be greatly appreciated.

Code:
Public Function RandomString(Optional ByVal arrList() As String = {"a","b","c"}) As String

        End Function



Wayne Sellars

"Programming, today is a race between software developers, striving to build bigger and better idiot-proof programs, and the Universe, trying to produce bigger and better idiots. So far, Universe 1 - Programmers 0."
 
Hi
Apart from the function signature and optional parameter thing,
Code:
        Dim strOtherArr As String() = {"a", "b"} 'valid
        Dim strNewArr As String() 'valid
        strNewArr = {"a", "b"} ' invalid
        strNewArr = New String() {"a", "b"} 'valid

But you can't use the last one in the function signature because a constant expression is required.

My suggestion is use an overload.

Code:
    Function strThing() As String
        'call the other version
        Return strThing(New String() {"a", "b", "c"})
    End Function

    Function strThing(ByVal strArrList As String()) As String
        'do something
    End Function

Mark [openup]
 
Hi wsellars,

You may not be able to do it the way you are trying instead what we can do is make the argument as Object and try the same. See the code below.

'Caller
Private Function myFunction() As Integer

Dim stringParm() As String
stringParm = New String() {"A", "B", "C"}
testFunction(stringParm)
End Function

'Function declaration
Private Function testFunction(Optional ByVal objectParm As Object = Nothing) As Integer

Dim myParm() As String

'Good to have some error handling here like
'If type passed in is an ArrayList or not etc.
myParm = objectParm

Return 1
End Function

This should work.
 
Thanks, I totally did not even think about overloading the function, which is something I need to do frequently.


Wayne Sellars

"Programming, today is a race between software developers, striving to build bigger and better idiot-proof programs, and the Universe, trying to produce bigger and better idiots. So far, Universe 1 - Programmers 0."
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top