vb.netvisual-studio

Issue with ByVal and Arrays in Functions (VB.NET)


I've ran into an issue with my code for the last week or so, and its been killing me trying to figure out what's wrong with it. I've extracted and isolated the issue from my main project, but the issue still isn't apparent.

Essentially, I have a function that usually does a lot of stuff, but in this example just changes 1 element in an array called FalseTable. Now, I have set this variable to be ByVal, meaning the original variable (ie: TrueTable) shouldn't change, however, it does! Here is the full code:

Dim TrueTable(7) As Char
    Sub Main()
        Dim FalseTable(7) As Char
        For x = 0 To 7
            TrueTable(x) = "T"
        Next
        For x = 0 To 7
            FalseTable(x) = "F"
        Next

        Console.WriteLine("before")
        For x = 0 To 7
            Console.Write(TrueTable(x))
        Next
        Console.WriteLine()
        Test(TrueTable)
        Console.WriteLine("result")
        For x = 0 To 7
            Console.Write(TrueTable(x))
        Next
        Console.WriteLine()

        Console.ReadLine()
    End Sub

    Function Test(ByVal FalseTable() As Char) As Char()
        FalseTable(0) = "0"
        Return FalseTable
    End Function

Now, I used to think that it was the repetition of the name "FalseTable" in the function, however even if I change the function to:

Function Test(ByVal SomeTable() As Char) As Char()
        SomeTable(0) = "0"
        Return SomeTable
    End Function

And not modify the rest, the issue still persists - for some reason, TrueTable is being updated when it shouldn't due to the ByVal status.


Solution

  • If you don't want to change the TrueTable, define another Array and copy TrueTable to it.

    Here's the code you can refer to.

    Dim TrueTable(7) As Char
    Dim TrueTable2(7) As Char
    Sub Main()
        For x = 0 To 7
            TrueTable(x) = "T"c
        Next
    
        Console.WriteLine("before")
        For x = 0 To 7
            Console.Write(TrueTable(x))
        Next
        Console.WriteLine()
    
        TrueTable.CopyTo(TrueTable2, 0)
        Test(TrueTable2)
        Console.WriteLine("result")
        For x = 0 To 7
            Console.Write(TrueTable(x))
        Next
        Console.WriteLine()
    
        Console.ReadLine()
    End Sub
    

    Result:

    enter image description here