Create multiline string literal in C#
This article illustrates the different techniques to create a multiline string literal in C#.
1. Using Verbatim String Literal
In C#, the @ symbol serves as a verbatim identifier. It can be used to indicate that a string literal is to be interpreted verbatim. The following example illustrates the effect of defining a verbatim string literal containing line breaks.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; public class Example { public static void Main() { string xml = @"<?xml?> <book> <name>Harry Potter</name> <author>J. K. Rowling</author> <language>English</language> <genre>Fantasy</genre> </book>"; Console.WriteLine(xml); } } |
Output:
<?xml?>
<book>
<name>Harry Potter</name>
<author>J. K. Rowling</author>
<language>English</language>
<genre>Fantasy</genre>
</book>
Starting with C# 6.0, you can use interpolated strings ($) with the verbatim string literal (@):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void Main() { string genre = "Fantasy"; string xml = $@"<?xml?> <book> <name>Harry Potter</name> <author>J. K. Rowling</author> <language>English</language> <genre>{genre}</genre> </book>"; Console.WriteLine(xml); } } |
Output:
<?xml?>
<book>
<name>Harry Potter</name>
<author>J. K. Rowling</author>
<language>English</language>
<genre>Fantasy</genre>
</book>
2. Using String.Join() method
Another alternative is to use the String.Join() method, which concatenates elements of a collection with the specified separator between each element. The following code example demonstrates how to create a multiline string literal with the String.Join() method using Environment.NewLine as a delimiter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { public static void Main() { string xml = String.Join( Environment.NewLine, "<?xml?>", "<book>", "\t<name>Harry Potter</name>", "\t<author>J. K. Rowling</author>", "\t<language>English</language>", "\t<genre>Fantasy</genre>", "</book>"); Console.WriteLine(xml); } } |
Output:
<?xml?>
<book>
<name>Harry Potter</name>
<author>J. K. Rowling</author>
<language>English</language>
<genre>Fantasy</genre>
</book>
That’s all about creating a multiline string literal in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)