In C#, I often use verbatim string literals (e.g., @"Arrr!"
) to break long strings across multiple lines while preserving the layout. For example, I use it to break up inline SQL like this:
var sqlString = @"
SELECT
Column1
, ...
FROM
Table1 INNER JOIN ...
WHERE
Column2 = @Value2
, ...
";
...or to break down a regex pattern like this:
var regexPattern = @"
(?<state>\w+)[.]? (?#*** Matches state {optionally having a period at the end} ***)
(\s+|,|,\s+|\s*\u2022\s*) (?#*** Matches space between state and zip {can include a comma or bullet point} ***)
(?<zip>(\d{5}-\d{4}\b|\d{5}(?![\w-]))) (?#*** Matches zip code ***)
";
If this code gets auto-indented later on, however, the verbatim string literal does not auto-indent. It gets left behind while the lines of code above and below it move to the right. The result is that it falls out of alignment with everything else. For example:
BEFORE:
verbatim = @" ___
I likes my |
strings purty | indented the way I like!
"; ___|
fooBar = "nomnom";
AFTER SURROUNDING WITH 'IF' STATEMENTS:
if (true)
{
if (maybe)
{
verbatim = @" ___
I likes my |
strings purty | no longer indented the way I like =(
"; ___|
fooBar = "nomnom";
}
}
How can I make Visual Studio auto-indent the lines of my verbatim string literal the same way it does with the other lines of code around it?
NOTES
I don't want to use normal strings on each line and concatenate them all together like this (this is how I used to do it but I find the free-form verbatim string literals so much easier to read and modify):
notverbatim =
"Alas! "
+ "This doth "
+ "make me sad =( "
;
Because indenting a multi-line verbatim string literal "grows the string" by adding new whitespace to the left of each line, I realize there are some verbatim string literals where this would not be desirable. If setting this behavior globally in Visual Studio would lead to unintended consequences by indenting other verbatim string literals that shouldn't be, is there a way to mark individual verbatim string literals in the code such that they get auto-indented while all others do not?
I was able to get VS2017 to behave this way by making a change to the "Indenting" settings. The one I changed was at Tools -> Options -> Text Editor -> C# -> Tabs. At the top of that screen is a section titled Indenting. Changing it from "Smart" to "Block" resulted in behavior that was similar to how VS2010 worked out of the box (at least for me).
I just made this change so I'm not sure of the full implications to other kinds of indenting, but for the verbatim strings it seems to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With