Search code examples
vb.netgenericsidisposableparamarray

How to implement a function that takes a param array (variable number of args) of generic args


I have seen a question here where they implemented a generic dispose method that takes any IDisposable object and calls dispose on it. I would like to make this such that it can take variable number of args. However, I do want to restrict the args to be IDisposable at compile time. (This is because some people in my organization will end up calling this method even on non IDisposable objects "Just to be safe" and "it causes no harm")

I have implemented the same in VB like this. How can I make it take multiple args. Note that I do want them to be passed by reference because I am setting the variable to nothing.

Public Sub DisposeObject(Of TDisposable As IDisposable)(ByRef disposableObject As TDisposable)
    If disposableObject IsNot Nothing Then
        disposableObject.Dispose()
        disposableObject = Nothing
    End If
End Sub

Solution

  • In VB you get a method with variable number of arguments with the ParamArray modifier on an array parameter.

    Note however that ParamArray parameters must be declared ByVal, and changes to the array have no effect in the calling code. So you can't have both variable number of arguments and ByRef semantics.