SCENARIO
I wrote these extension methods to initialize and/or dispose all the elements of an Array in a elegant/simplified way to avoid code repetition:
<HideModuleName>
Public Module ArrayExtensions
<Extension>
Public Sub InitializeAll(Of T As New)(ByVal sender As T())
For index As Integer = 0 To (sender.Length - 1)
sender(index) = New T
Next index
End Sub
<Extension>
Public Sub InitializeAll(Of T As IDisposable)(ByVal sender As T())
ArrayExtensions.DisposeAll(sender)
For index As Integer = 0 To (sender.Length - 1)
sender(index) = Activator.CreateInstance(Of T)()
Next index
End Sub
<Extension>
Public Sub DisposeAll(Of T As IDisposable)(ByVal sender As T())
For index As Integer = 0 To (sender.Length - 1)
If (sender(index) IsNot Nothing) Then
sender(index).Dispose()
sender(index) = Nothing
End If
Next index
End Sub
End Module
The intention is to use it in common scenarios like this:
Dim myCollection As MyDisposableType() = New MyDisposableType(100) {}
myCollection.InitializeAll()
myCollection.DisposeAll()
PROBLEM
The problem I found is that the compiler is showing this error:
'Public Sub InitializeAll(Of T As New)(sender() As T)' has multiple definitions with identical signatures.
...I don't really understand this error since IDisposable is a interface, I tried to remove the "As New" of the type parameter but still showing the same error.
QUESTION
How I could adapt the type parameters of the InitializeAll() methods to avoid this error and still working in the expected behavior?, I mean that one method accepts an array of disposable objetcs, and the other method for non-disposable objects.
I'm aware that I could fuse/merge the logic of both methods in a single method like this below:
<Extension>
Public Sub InitializeAll(Of T As New)(ByVal sender As T())
For index As Integer = 0 To (sender.Length - 1)
If (sender(index) IsNot Nothing) Then
If sender(index).GetType.GetInterfaces.Contains(GetType(IDisposable)) Then
DirectCast(sender(index), IDisposable).Dispose()
sender(index) = Nothing
End If
End If
sender(index) = New T
Next index
End Sub
But I prefer to have two different methods, because then I gain performance avoiding additional checks when I'm not passing an Array of disposable objects.