mamu
mamu

Reputation: 12414

F# string.Format

I am writing my first F# library

I am trying to use string.Format and it complains that no such function exists.

Is it not available or am I doing something wrong?

Upvotes: 52

Views: 27593

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243041

If you want to avoid using the full name, you can use open in F#:

open System
let s = String.Format("Hello {0}", "world")

This should work in both F# interactive (enter the open clause first) and in normal compiled applications. The key thing is that you must write String with upper-case S. This is because string in C# isn't a usual type name - it is a keyword refering to the System.String type.

Alternatively, you could also take a look at the sprintf function. It is an F#-specific alternative to String.Format which has some nice benefits - for example it is type checked:

let s = sprintf "Hello %s! Number is %d" "world" 42

The compiler will check that the parameters (string and int) match the format specifiers (%s for string and %d for integers). The function also works better in scenarios where you want to use partial function application:

let nums = [ 1 .. 10 ]
let formatted = nums |> List.map (sprintf "number %d")

This will produce a list of strings containing "number 1", "number 2" etc... If you wanted to do this using String.Format, you'd have to explicitly write a lambda function.

Upvotes: 114

Yin Zhu
Yin Zhu

Reputation: 17119

the full name of it is:

System.String.Format

Upvotes: 3

Related Questions