Calling ToString with a nominated format returns Char rather than String

70 Views Asked by At

I am making a generic method to print an array to a delimited string, and the ToString() method is behaving strangely. Take this function:

Public Function ToString(Of T)(array() As T, delimiter As String, format As String) As String
    Dim resultBuilder As New StringBuilder

    If array IsNot Nothing AndAlso array.Count > 0 Then
        For i As Integer = 0 To array.Count - 1
            If i Then resultBuilder.Append(delimiter)

            resultBuilder.Append(array(i).ToString(format))
        Next
    End If
    Return resultBuilder.ToString
End Function

and present it with

Dim a() As Integer = {32, 14, 7, 0}

Label1.Text = ToString(a, ", ", "0000")

I would expect the function to return

0032, 0014, 0007, 0000

instead the function is returning

3, 1, 7, 0

I assume the problem is the ToString() function is struggling to know what type it is being applied to, but the debugger is keenly aware that T is Integer and knows otherwise how to correctly format an integer in the Watch. No matter the type, the behaviour is still unusual. What on earth is going on?

0

There are 0 best solutions below