We all know how it goes. As soon as we are adding a bit of juice to our strings, it get’s messy. As I was building a modal for my UI System and writing down some placeholder texts, my OCD began to tingle.
string message = $"Do you want to leave this level? \n Loot collected: {coinpercent} % <sprite=\"uiicons\" name=\"coin\">";
I dont know why, but the standard “escape with backslash” approach is somewhat unreadable for me. One method would be to shift the problem and use string interpolation like that example below, but that also makes it a bit more complicated.
string spriteTag = "<sprite=\"uiicons\" name=\"coin\">";
string title = $"Do you want to leave this level? \n Loot collected: {coinpercent} % {spriteTag}";
Precede with @ and use double quotes
A quick google search later (ChatGPT failed) I found another approach, that I was unaware of.
If you precede the string with the “@” character, you can use a double set of quotation marks to indicate a single set of quotation marks within a string. If you prefix the string with the “@” character, you can use a set of double quotation marks to specify a single set of quotation marks within a string. And it makes it more readable. Have a look:
//Standard Method
string message = $"Do you want to leave this level? \n Loot collected: {coinpercent} % <sprite=\"uiicons\" name=\"coin\">";
//String Interpolation
string spriteTag = "<sprite=\"uiicons\" name=\"coin\">";
string title = $"Do you want to leave this level? \n Loot collected: {coinpercent} % {spriteTag}";
//@Method
string message = $@"Do you want to leave this level?
Loot collected: {coinpercent} % <sprite=""uiicons"" name=""coin"">";
One Caveat however: The @ character in C# treats the string as a verbatim string literal, which means it includes all whitespace and line breaks exactly as they are written. This includes the indentation at the start of the line. So if you are in Code and use indentation, it gets shifted.
But nevertheless. Cool to learn some different approaches.