Everything You Wanted to Know About Multiline Strings

Working with strings is probably one of the earliest things we get to do as C# developers. In fact, if you consider that most of us start with the “Hello, World!” example, you’re being exposed to the string type right away. But as you continue to use strings, you’ll quickly find that you want to work with strings that span multiple lines and how we define multiline strings might be a tricky topic for beginners.

No sweat! In this article, we’ll look at some simple code examples that demonstrate how to define multiline strings. I’ll also link over to GitHub where you can see this code committed and pushed up to a public repository. Finally, the last example contains a special bonus that I think you’ll like (even if it’s a slightly more advanced topic). Read until the end!

The Base Case

This is the most simple example, where we just assign some text between double quotes to a string variable. This is our base case to compare against when we start looking to multiline things. This example is all declared on a single line, and the resulting string has no line breaks in it either. As easy as it gets!

var simpleString = "Hello, World!";
Console.WriteLine(simpleString);

As you might expect, the output looks something just like this:

Hello, World!

Multiline Strings in One Line of Code

Our next example is perhaps the most simple way to multiline a string. However, it is important to note that this example looks at creating a multiline string where the resulting value of the string is across multiple lines. The string itself in code is still all defined on one line

var multilineString = "Hello,rnWorld!";
Console.WriteLine(multilineString);

This example shows the carriage return (r) and linefeed (n) characters added into the string to make the output span across two lines. These line endings can be different on Windows vs unix so consider using Environment.NewLine. It’s also important to note that we use the backslash here which makes it an escape character (and that’s why you don’t see an extra r and n in the console output):

Hello,
World!

Multiline Strings in Multiple Lines of Code

This is much like the previous example, except we will use the + operator to concatenate the strings. This string is now across multiple lines in our code AND multiple lines in the output.

var multilineString = 
    "Hello,rn" +
    "World!";
Console.WriteLine(multilineString);

Because we have two constant strings being concatenated together, the compiler will treat these as one single string for us. However, it afforded us the ability to split the string across multiple lines when we created it so that it was perhaps easier to read.

The output is exactly the same as the previous example:

Hello,
World!

Single Line String Across Multiple Lines of Code

Now we’re on a roll. So what happens if we want to be able to use the string concatenation operator (+) but we don’t want the result to be a multiline string? Simple! We can remove our new line characters r and n.

var stringAcrossMultipleLines =
    "Hello" +
    "," +
    " " +
    "World" +
    "!";
Console.WriteLine(stringAcrossMultipleLines);

The output of this will therefore print to one single line in the console as follows:

Hello, World!

Multiline Strings as Verbatim Strings

This example gets a little bit fancier! I would argue that this is probably (until recently) one of the more popular ways to declare multiline strings in your code. It gives you the benefit of having multiline strings with respect to their resulting value, but they also easily span multiple lines of code without having to put a string concatenation operator (+) at the end of every line.

Let’s look at the example:

var verbatimString = @"Hello,
    world! I wonder if this 
    string will have funny 
    gaps even though it
    looks like it is 
    aligned to the same
    indentation in the editor...";
Console.WriteLine(verbatimString);
Console.WriteLine();

The @ symbol at the start of the string definition (i.e. right before the double quotes) marks the string as verbatim. This example is a little bit contrived, because I wanted to illustrate one of the pitfalls of this method if you’re not aware of it. Verbatim strings will include all of your indentation as part of the actual string itself! Sometimes this might be what you expect (truly, it is verbatim) and other times it might be a bit frustrating.

Here’s the output:

Hello,
    world! I wonder if this
    string will have funny
    gaps even though it
    looks like it is
    aligned to the same
    indentation in the editor...

A New Challenger Approaches: Raw String Literals

In C# 11 we get access to this new fancy feature called raw string literals. This might be old news if you have seen other programming languages with similar functionality, but it’s big news for us C# developers.

I view the raw string literal option as being much like a verbatim string, but without the worry about indentation. We can denote a raw string literal with triple quotes, and if we have a string with triple quotes inside of it already, we can use four quotes as well. This pattern repeats based on how many quotes you need to support.

Let’s check out the example:

var rawStringLiteral = 
// Note: try playing with the indentation of all of the lines here
        """
        "Hello,
        world!" I wonder if this 
        string will have funny 
        gaps even though it
        looks like it is 
        aligned to the same
        indentation in the editor...
            Maybe just
            these lines
            right here.
        """;
Console.WriteLine(rawStringLiteral);

In the example above, we have DOUBLE indented the string, but the Visual Studio IDE will actually give you a visual indicator as to where the start of the line actually is. In this case, it’s directly in line with the left side of the triple quotes.

That means our output is going to look like this:

"Hello,
world!" I wonder if this
string will have funny
gaps even though it
looks like it is
aligned to the same
indentation in the editor...
    Maybe just
    these lines
    right here.

It’s important to note only the last few lines were actually indented, even though all of the lines were indented in the code. That’s just because of where the alignment gets set with the raw string literals. In my opinion, something I will be using a TON of for my multiline strings.

Here’s the output in the console from all of our examples:

C# multiline strings output

Bonus Round!

Alright, I did promise a bonus at the start of this article and I wasn’t lying. Raw string literals are a feature that comes in C# 11. But what happens if you are targeting an older version of .NET and want to access this feature?

Fortunately, I have covered this topic in a previous article, but we can elaborate on it here too. Essentially, we can use a nuget package called PolySharp and set the LangVersion attribute in the csproj file to be 11.0. If you have your build machine setup with C# 11 requirements, it will allow you to compile the code for raw string literals on older framework versions.

Don’t believe me? You can prove it for yourself when you go look at the code I have pushed up to GitHub for this article!

Conclusion

Strings are an essential building block for all of us C# developers, and creating a multiline string is a common occurrence for many of us. Depending on your skill level and familiarity, you might not know the various ways you can create a multiline string. It’s also important to decide whether or not you want to have a multiline string with respect to how it looks in code, how the result value is actually formatted, or both! The methods in this article should help you decide and start writing tons of multiline strings!

Nick Cosentino

Principal Software Engineering Manager at Microsoft. Views are my own.

Leave a Reply