Multiline String Literal in C#

Multiline string literal in C#

You can use the @ symbol in front of a string to form a verbatim string literal:

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

You also do not have to escape special characters when you use this method, except for double quotes as shown in Jon Skeet's answer.

How to get Multiline string

Take a look at interpolated strings for including your field values.

For the new lines, there are three distinct items to be aware of: the Enivronment.NewLine constant, the \n character literal, and the HTML <br> element. The last is especially important for emails which use an HTML body.

In this case, I suggest a C# mult-line string literal, with an interpolated value for an extra end line you can set or not as needed based on the platform.

So you end up with this:

string br = ""; // set this to "<br>" for HTML emails

string EmailBody =
$@"Request no.- ('{objUserModel.ID}') has been raised for special{br}
vehicle by requester-( '{RequesterInfo}').{br}
{br}
ORG_Unit:'{objUserModel.OrgUnit}'{br}
TDC:'{objUserModel.TDC}'{br}
Customer Name:'{objUserModel.CustName}'{br}
Supply Plant:'{objUserModel.CustName}'";

The original code was having trouble because of the concatenation. Each line of code for the string was broken up at the end like this: " +, to continue again with a new string literal on the next line. In this way, the line breaks in the code were lost in the resulting string.

The code here addresses this issue by putting everything into the same string literal. There is only one set of double quotes defining the entire string, which now includes the line breaks built into the code. The one thing to be aware of with this technique is you want to shift your strings all the way to the left, regardless of any other indentation in the code.

Multiline C# interpolated string literal

You can combine $ and @ together to get a multiline interpolated string literal:

string s =
$@"Height: {height}
Width: {width}
Background: {background}";

Source: Long string interpolation lines in C#6 (Thanks to @Ric for finding the thread!)

Multiline string with added text from variables

One option is to use string formatting instead. Before C# 6:

string pattern = @"this is a multiline text
this is {0}
this is {1}
this is {2}";

string result = string.Format(pattern, a1, a2, a3);

With C# 6, you can use an interpolated verbatim string literal:

string pattern = $@"this is a multiline text
this is {a1}
this is {a2}
this is {a3}";

Note that $@ has to be exactly that - if you try to use @$, it won't compile.

In C#, what's the best way to spread a single-line string literal across multiple source lines?

I would use a variation of your method:

string longString =
"Lorem ipsum dolor sit amet, consectetur adipisicing " +
"elit, sed do eiusmod tempor incididunt ut labore et dolore magna " +
"aliqua. Ut enim ad minim veniam.";

Here I start the string on the line after the equals sign so that they all line up, and I also make sure the space occurs at the end of the line (again, for alignment purposes).

Multiline string variable

You (initially) marked this as c#, but show VB code. For c#: use the @ specifier:

string myText =
@"line 1
line 2
line 3"

Note that if you don't want a blank line at the start of your string, make sure you put the @" on the same line as the first line of your text, as I've done above.

For VB.NET, there is no direct support for this, but you can use the nice hack from this answer to get around it:

Dim s As String = <a>line 1
line 2
line 3</a>.Value

Also consider creating a string resource; you can add line breaks in there (ensure you use shift-enter, per the note in this answer), then load the resource using something similar to

Dim myString As String = My.Resources.MyString

Update for Visual Studio 2015: Obviously vb.net was the difficult case here, but as of VS2015 it supports multi-line strings in a fashion similar to c# verbatim strings, but without the preceding @.

Note that the line terminators embedded in the string are the actual line terminators provided by your editor of choice. For VS this is \r\n.

Example:

Sample Image

Source here.

For the new interpolated strings introduced in VS2015 / C# 6, prefix the string with $@ in C#:

string multiline = $@"
[configuration]
name=Fred
age={age}";

In VB.NET, just leave out the @:

Dim multiline As String = $"
[configuration]
name=Fred
age={age}"

Double quotes in c# doesn't allow multiline

If you really need to do this in a string literal, I'd use a verbatim string literal (the @ prefix). In verbatim string literals you need to use "" to represent a double quote. I'd suggest using interpolated string literals too, to make the embedding of title and message cleaner. That does mean you need to double the {{ and }} though. So you'd have:

string title = "This is the title: ";
string message = "(Message)";
string str = $@"
{{
""aps"":
{{
""alert"":""{title}{message}""
}}
}}";
Console.WriteLine(str);

Output:

{
"aps":
{
"alert":"This is the title: (Message)"
}
}

However, this is still more fragile than simply building up JSON using a JSON API - if the title or message contain quotes for example, you'll end up with invalid JSON. I'd just use Json.NET, for example:

string title = "This is the title: ";
string message = "(Message)";
JObject json = new JObject
{
["aps"] = new JObject
{
["alert"] = title + message
}
};
Console.WriteLine(json.ToString());

That's much cleaner IMO, as well as being more robust.



Related Topics



Leave a reply



Submit