Results 1 to 2 of 2

Thread: List(Of T) as optional function argument

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jun 2007
    Location
    India
    Posts
    1,158

    List(Of T) as optional function argument

    I want to specify an List(Of String) as an Optional function argument. But i am unable to initialize it in the function declaration. Can You plz show me how is it done.

    Thanks

  2. #2
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: List(Of T) as optional function argument

    The only option is to supply Nothing as the default value. Then, in the function, you would check if the list is Nothing, and if it is you assume it has not been passed.

    Code:
    Private Sub SomeMethod(ByVal x As Integer, Optional ByVal list As List(Of String) = Nothing)
       If list Is Nothing Then
          ' list has not been passed
       End If
    End Sub
    So you can't really distinguish between someone not passing anything and someone passing 'Nothing', such as this
    Code:
    Me.SomeMethod(32, Nothing)
    If you absolutely need to then you can simply define the same method twice, with different parameters. In that case you can supply whatever value you want for the list:
    Code:
    Private Sub SomeMethod(ByVal x As Integer)
       Dim newList As New List(Of String)
       newList.AddRange({"A", "B", "C"})
       Me.SomeMethod(x, newList)
    End Sub
    
    Private Sub SomeMethod(ByVal x As Integer, ByVal list As List(Of String)
       ...
    End Sub

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width