For readability purposes, sometimes we have to split a string into a multiline string in C#.
To our luck, there are several ways by which we can have multiline strings in C#.
Let's see a few ways how we can add multiline strings in C#.
- C# Multiline Strings Using + Operator To Concatenate Strings
- C# Multiline Strings Using The @ Symbol To Form A Verbatim Identifier
- C# Multiline Strings Using System.Environment.NewLine
C# Multiline Strings Using The + (plus) Symbol To Concatenate Strings
We can concatenate multiple strings in C# using the plus (+) symbol in C#.
Using the plus concatenation symbol, we can combile multiple strings together, even when they are in multiple lines.
Let's see this multiline string code example.
var message = "This is a long string which " + "we are continuing on the next line. " + "So this string is comprised of a multiline string in C#."; // Display Console.WriteLine(message);
Result:
This is a long string which we are continuing on the next line. So this string is comprised of a multiline string in C#.
C# Multiline Strings Using The @ Symbol To Form A Verbatim Identifier
Let's look at another example in which we can form Multiline strings in C#.
In this example, we will use the @ symbol to write multiline strings in C#.
Let's see this in example.
var message = @"This is a long string which we are continuing on the next line. So this string is comprised of a multiline string in C#."; // Display Console.WriteLine(message);
Result:
This is a long string which we are continuing on the next line. So this string is comprised of a multiline string in C#.
As you can see in the above example, when you use the @ symbol, you don't get the string in a single line. The @ symbol creates the string as you see. The second line comes in the second line. so it's not creating a concatenated string, it's creating a multiline string.
C# Multiline Strings Using System.Environment.NewLine
Similar to the above example, if you actually want to add line breaks to strings or multiline strings in C#, you can use the System.Environment.NewLine property and concatenate strings by adding a new line in between them.
Let's see this in an actual example.
var message = "This is a long string which " + System.Environment.NewLine + "we are continuing on the next line. " + System.Environment.NewLine + "So this string is comprised of a multiline string in C#."; // Display Console.WriteLine(message);
Result:
This is a long string which we are continuing on the next line. So this string is comprised of a multiline string in C#.