Search code examples
vb.netoptional-parametersempty-list

Set the default value of an optional 'List(Of t)' parameter to an empty list?


In this example, I can't figure out how to set the optional parameter c to an empty List(Of thing):

Sub abcd(a as something, b as something, optional c as List(Of thing) = ?? )
    ' *stuff*
End Sub

I considered setting c to null, but that seems like a bad thing to do.


Solution

  • You can't. Optional values have to be compile-time constants. The only compile-time constant you can assign to List(Of T) is Nothing.

    What you can do is overload that method with one that omits the List(Of T)parameter. This overload can then pass an empty List(Of T) to the original method:

    Sub abcd(a as something, b as something)
        abcd(a, b, New List(Of T)())
    End Sub
    
    Sub abcd(a as something, b as something, c as list(of thing))
        doStuff()
    End Sub