MSX
MSX

Reputation: 359

F# force an overload of System.String.Format

I would like to format a string using System.String.Format which has 5 overloads:

String String.Format(String format , Object arg0 )
String String.Format(String format , Object arg0 , Object arg1 )
String String.Format(String format , Object arg0 , Object arg1 , Object arg2 )
String String.Format(String format , params Object[] args )
String String.Format(IFormatProvider provider , String format , params Object[] args )

I would like to use the fourth overload (the one that takes an array of objects) like this:

let frm = "{0} - {1}"
let args = [| 1; 2 |]
System.String.Format(frm, args)

The problem is that the args argument is interpreted as an Object and hence the first overload is called. So correctly I get the following error:

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

Is there a way to force the "correct" overload?

Upvotes: 3

Views: 209

Answers (2)

pad
pad

Reputation: 41290

A more elegant variant of @John's answer is to add type annotation so that the compiler will do automatic upcast on all elements of an array:

let frm = "{0} - {1}"
let args : obj [] = [| 1; 2 |]
System.String.Format(frm, args)

Upvotes: 9

John Palmer
John Palmer

Reputation: 25516

You can force the correct overload by switching each element of the array to an object like so:

let frm = "{0} - {1}"
let args = [| 1:> obj; 2 :>obj|]
System.String.Format(frm, args);;

or if you have a longer list

let frm = "{0} - {1}"
let args = [| 1; 2 |] |> Array.map (fun t ->t:> obj)
System.String.Format(frm, args);;

Upvotes: 2

Related Questions