Question Array in Queue

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
Could the "abc" and "def" be directly enter into Q1 without making the tempArray?

VB.NET:
     Dim Q1 As New Queue(Of String())(30)


     Dim tempArray(1) As String
     tempArray(0) = "abc"
     tempArray(1) = "def"
                
     Q1.Enqueue(tempArray)
 
It depends what you mean by 'tempArray'. Remember, arrays a just objects like everything else so 'tempArray' is just a variable like any other and it refers to a String array object. If you want a Queue containing String arrays then you have to create the String arrays, but you don't necessarily need a variable to assign them to. The Enqueue method simply requires a reference to an array. You can use any expression there that evaluates to a String array reference. As you're using .NET 4.0 you can even infer the type, making it simpler still:
VB.NET:
Q1.Enqueue({"abc", "def"})
 
what if i have a queue of arrays, and i want to send it as the variable to a function that need a 2d array. Do i need to dequeue all the arrays from the queue and put it in a 2d array first?


VB.NET:
    Dim a As New Queue(of String())(10)
    a.enqueue({"aa","bb"})
    a.enqueue({"cc","dd"})
    a.enqueue({"ee","ff"})

    Dim b(1, a.Count - 1) As String

    For i As Integer = 0 To a.Count - 1
            b(0, i) = a.ElementAt(i).ElementAt(0)
            b(1, i) = a.ElementAt(i).ElementAt(1)
    Next

    test(b)


    Public Function test(array As String(,)) As String
    
    end Function
 
Last edited:
Arrays are no different to any other objects. If a method expects a 2D array then you have to pass it a 2D array. Is a Queue of 1D arrays a 2D array? The answer to that is fairly obvious. If a method expects an object of a particular type then you have to pass it an object of that type. That rule is relaxed somewhat if you have Option Strict Off, which you should pretty much never do, but, even then, the method still requires an object of the type it expects so the system has to be able to implicitly convert the object you pass. That is only possible for simple types, e.g. Integer to String. For complex types like Queue(Of String()) there is definitely no implicit conversion possible. Presumably when you ran that code for yourself the compiler would have told you that one could not be converted to the other.
 
Back
Top