Adam
Adam

Reputation: 6152

String.Format: Index (zero based) must be greater than or equal to zero and less than the size of the argument list

I'm trying to format a string, using an array of values:

Dim args(2) As Object
args(0) = "some text"
args(1) = "more text"
args(2) = "and other text"

Test(args)

The function Test is:

Function Test(ByVal args As Object)
    Dim MailContent as string = "Dear {0}, This is {1} and {2}."

    'tried both with and without converting arr to Array
    args = CType(args, Array)

    MailContent = String.Format(MailContent, args) 'this line throws the error: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

End Function

Upvotes: 0

Views: 444

Answers (1)

Ry-
Ry-

Reputation: 225095

Why are you using Object as the type for args? You’re just throwing away all your type information.

Dim args As String() = {
    "some text",
    "more text",
    "and other text"
}

Test(args)
Sub Test(args As String())
    Dim mailTemplate As String = "Dear {0}, This is {1} and {2}."
    Dim mailContent As String = String.Format(mailTemplate, args)
End Sub

String.Format accepts a ParamArray of objects, so it’ll let you pass one (args; CType(a, T) is just an expression producing a value of type T and wouldn’t magically change the type of args even if you cast to the right type) and treat it as a single-element array.

You might need to use String.Format(mailTemplate, DirectCast(args, Object())), too. I can’t check.

Upvotes: 2

Related Questions