I'm trying to create a method to perform both increment and value assignment operations, something like this:
Public Sub ArrayAdd(ByRef arr As Object(), newItem As Object)
Try
If IsNothing(arr) Then
arr = New Object() {newItem}
Exit Sub
End If
Array.Resize(arr, arr.Length 1)
arr(arr.Length - 1) = newItem
Catch ex As Exception
Throw New ApplicationException(ex.Message, ex)
End Try
End Sub`
Using this method generates type conversion errors, so I would like to use generics Of T
(without success).
CodePudding user response:
A generic method works exactly as you'd expect:
Public Sub AppendElement(Of T)(ByRef array As T(), element As T)
If array Is Nothing Then
array = {element}
Else
Dim upperBound = array.Length
System.Array.Resize(array, upperBound 1)
array(upperBound) = element
End If
End Sub
CodePudding user response:
Here's the method implementation
Public Sub ArrayAdd(Of T)(ByRef arr() As T, item As T)
Try
If IsNothing(arr) Then
arr = New T() {item}
Exit Sub
End If
Array.Resize(arr, arr.Length 1)
arr(arr.Length - 1) = item
Catch ex As Exception
Throw New ApplicationException(ex.Message, ex)
End Try
End Sub