Search code examples
stringf#multilinestring

what's the best way to hardcode a multiple-line string?


In unit test I would like to hard code a block of lines as a string.

In C# I would do

var sb = new StringBuilder();
sb.AppendLine("myline1");
sb.AppendLine("myline2");
sb.AppendLine("myline3");

Since I converted to F# I tried to minimize the usage of .Net method by using bprintf instead, but somehow there is no bprintfn support which seems strange to me.

It is tedious to add \r\n at the end of each line manually.

Or is there any better way than StringBuilder?


Solution

  • I think there is no problem with using StringBuilder in F# as you did.

    There is a function fprintfn in Printf module, so you can use it with a StringWriter object:

    let sw = new StringWriter()
    fprintfn sw "myline1"
    fprintfn sw "myline2"
    fprintfn sw "myline3"
    sw.ToString()
    

    I like fprintf and fprintfn since they are flexible. You can write to console output by supplying stdout instead.