Search code examples
vb.netpass-by-value

Is there a method to add to a list (of list(of String)) byVal?


I'd like to repeatedly add lists of strings to a bigger list collection, but it seems that the list.add function is adding the items byref. How can I change the below example code to pass the elements byval so that they're not cleared when I re-use variables:

    Dim inner As New List(Of String)
    Dim outer As New List(Of List(Of String))
    Dim eleCount As Integer = 0
lbltop:
    inner.Add("a")
    inner.Add("b")
    inner.Add("c")

    outer.Add(inner)
    Debug.Write(outer(0)(0).ToString())
    inner.Clear()

    Debug.Write(outer(0)(0).ToString())

    eleCount += 1
    If eleCount < 2 Then
        GoTo lbltop
    End If

this writes a then there's an out of range exception for the next debug.write statement.

I'd like it to write aa then loop to add another inner element.


Solution

  • List<T> is a reference type. Only way to not effect it when calling Clear() is to add a clone of it to outer instead. You can do so by using .ToList()

    outer.Add(inner.ToList())
    

    But I actually think the most clear way is to instead assign inner a new List instead of calling Clear, than you dont have to do above.

    inner = new List(Of String)