views:

35

answers:

3

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
A: 

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.

Mattias S
So, is this specific to Vb.Net. Can the same be implemented in C# ?
DevByDefault
No, it works more or less the same in C#.
Mattias S
A: 

Donno VB but in C# you could write:

public void DisposeObjects(params IDisposable[] args)
{
  foreach(IDisposable obj in args)
  {
     if(obj != null)
     {
        obj.Dispose();
     }
  }
}
AZ
A: 

Here is how you do it:

Public Sub DisposeObject(ByVal ParamArray disposableObjects() As IDisposable)
    For Each obj As IDisposable In disposableObjects
        If Not IsNothing(obj) Then obj.Dispose()
    Next
End Sub

But I do not recommend such a solution. It's much better to use the "using" statement.

In c#

using (var obj = new TypeImlementingIdisposable)
{
   //do stuff with the object here
}

and in vb:

Using obj As New TypeImlementingIdisposable
   ' do stuff with the object here
End Using

This ensures that the objects always are disposed, not matter if an exception is thrown or not.

You can read more at msdn

jgauffin
I agree that using "Using" is a better way, but at the moment the only change I can make to existing code is in the Finally block. I will be calling this method in the Finally Blocks, that way they will get disposed even on Exceptions.
DevByDefault