C# / Unity Tip: Embedding quotes within a string

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.

C#
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.

C#
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:

C#
//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.

C# / Unity Tip: Get the index from end of an array or list

So, I was in the midst of developing my game when I wanted to retrieve the penultimate (I looked it up, it exists) member of my pathfinding array to determine if the point before the ULTIMATE target is reachable. So, naturally, I used the old self-referencing line to get the work done and created a static method to do the job.

C#
        ...PathExtensions.GetPositionOnPath(path, path.vectorPath.Count -2)...        
        
        /// Method to retrieve the index from the end
        
        public static Vector3 GetPositionOnPath(Path path, int i)
        {
            return path.vectorPath[i];
        }

But wait! Something in the deeper parts of my brain itched. There was some other way to achieve this much more elegantly. And yes, I was right! Again!

INTRODUCING THE ^_____^

After a quick Google search, I found the answer. With C# 8.0 and later, you can indeed use the caret symbol (^) to index arrays, which is known as the “index from end” feature. Nice! It is now much more readable and easier to maintain.

C#
        ...PathExtensions.GetPositionOnPath(path,^2)...
        
        /// Much simpler method to retrieve the index from the end
        
        public static Vector3 GetPositionOnPath(Path path, Index i)
        {
            return path.vectorPath[i];
        }

Some examples:

C#
        string[] colors = { "red", "blue", "green", "yellow", "orange", "purple", "pink", "brown", "black", "white" };

        // Accessing the last element of the array:
        Debug.Log(colors[^1]);
        // Output: "white"

        // Accessing the second to last element of the array:
        Debug.Log(colors[^2]);
        // Output: "black"

        // Accessing the third element of the array:
        Debug.Log(colors[^3]);
        // Output: "brown"

        // Accessing the first element of the array:
        Debug.Log(colors[^10]);
        // Output: "red"

Hope that helps! Bye.

Official documentation:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#index-from-end-operator-