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

colinfang picture colinfang · Jan 29, 2013 · Viewed 9.9k times · Source

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?

Answer

Kit picture Kit · Jan 30, 2013

Little known feature: you can indeed indent string content - by ending each line with a backslash. Leading spaces on the following line are stripped:

let poem = "The lesser world was daubed\n\
            By a colorist of modest skill\n\
            A master limned you in the finest inks\n\
            And with a fresh-cut quill.\n"

You will still need to include \n or \n\r at line ends though (as done in the example above), if you want these embedded in your final string.

Edit to answer @MiloDCs question:

To use with sprintf:

let buildPoem character =
    sprintf "The lesser world was daubed\n\
             By a colorist of modest skill\n\
             A master limned %s in the finest inks\n\
             And with a fresh-cut quill.\n" character

buildPoem "you"            
buildPoem "her"
buildPoem "him"