user1889116
user1889116

Reputation:

How do I concatenate a string array to a queue correctly?

I have a queue of strings:

Public Class QueueClient
    Private gaoFiles As New Queue(Of String)

and in a property call a function with the intention to concatenate an array of strings to the queue of strings:

    Public Property AddFiles As String()
        ...
        Set(asValue As String())
            AddFilesToQueue(asValue)
        End Set
    End Property

This is the called function, in which I attempt to perform the concatenation.

    Private Sub AddFilesToQueue(asFiles() As String)
        gaoFiles = CType(gaoFiles.Concat(asFiles), Queue(Of String))
    End Sub
End Class

This gets me an InvalidCastException (I have Option Strict On).

I understand, that

   gaoAudioFiles.Concat(asFiles)

tries an implicit conversion from a string array to a Queue(Of String), which is not done due to my setting.

How do I cast this correctly?

gives me

Upvotes: 0

Views: 270

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415880

This doesn't work at all how you think.

The Concat() method on the Queue(Of T) type is inherited from IEnumerable(OF T), and it's using that implementation, meaning all you get back is an IEnumerable(Of T). This would be okay (though not very efficient) if you could cast IEnumerable(Of T) to a Queue(Of T), but that cast doesn't exist. Instead, you'll have to Enqueue each item:

Private Sub AddFilesToQueue(asFiles() As String)
    For Each file As String in asFiles
        gaoFiles.Enqueue(file)
    Next file
End Sub

It's also kind of weird to use a Property in this way. When you use assignment semantics, the end user expects a variable to be entirely replaced with the a new value. Appending via assignment semantics is not normal. Better to settle for the just the method... but you can make the method more useful like this:

Public Sub AddFilesToQueue(asFiles As IEnumerable(Of String))
    For Each file As String in asFiles
        gaoFiles.Enqueue(file)
    Next file
End Sub

You can still pass an array directly to that method. You can also pass a List(Of String) or any other sequence that inherits from IEnumerable (and there are many).

Upvotes: 1

Related Questions