C# 11 – Raw String Literals

The C# language received a slew of new features in version 11.0. Let’s begin with a feature called Raw String Literals.

Before we get into Raw String Literals, let’s take a look at the evolution of strings in C#, beginning with C# 1.0. All of these concepts are still applicable in C# 11.0.

Quoted String Literals in C# 1.0

Since C# 1.0, you can declare and initialise a string in the following manner:

string welcomeMessage = "Hello \"Niki\"";

Alternatively, to define a carriage return, use \r, and to define a new line, use \n. So, this string will start a new line with the name Tandel:

string fullname = "Niki\r\nTandel";

For C# strings, there are several other escape sequences. But it gets really interesting when it comes to filepaths and folderpaths, which on Windows usually include backslashes by default. However, as you may have noticed, a backslash is used to begin an escape sequence. As a result, C# looks for a specific character after the backslash, such as n for a new line, by default. To use a backslash in a string, it must be preceded by another backslash. You use to define a backslash in the same way that you use to define a double quote. The following statement is used to define a string with the value C:\Users\Folder\Documents:

string folderPath = "C:\\Users\\Niki\\Documents";

This brings us to the next type of string literal, verbatim string literals.

Verbatim String Literals in C# 1.0

A verbatim string literal begins with @”. It’s ideal if your string includes backslashes, quotes, or multiple lines. Take a look at the folder path below. Because the verbatim string literal does not look for escape sequences that begin with a backslash, you can use the backslash like any other character:

string folderPath = @"C:\Users\Niki\Documents";

Verbatim string literals are also useful for multi-line strings. The following two string variables have the same content, but the first is defined with a quoted string literal, while the second is defined with a verbatim string literal:

// Quoted string literal
string fullname1 = "Niki\r\nUpendra\r\nTandel";

// Verbatim string literal
string fullname2 = @"Niki
Upendra
Tandel";

Simply write two double quotes inside a verbatim string literal to define a double quote (as a single one ends the string). This is demonstrated in the following snippet. Hello “Niki,” once again, both variables contain the same string:

// Quoted string literal
string welcomeMessage1 = "Hello \"Niki\"";

// Verbatim string literal
string welcomeMessage2 = @"Hello ""Niki""";

Concatenate and Format Strings in C# 1.0

To use C# variables within a string, concatenate strings with the + character, as shown below. The string Niki Tandel: is now stored in the fullName variable.

string firstName = "Niki";
string lastName = "Tandel";

string fullName = firstName + " " + lastName;

You can also use the string. Format method for using variables in a string, as shown below. The string Niki Tandel is also present in the fullName variable.

string firstName = "Niki";
string lastName = "Tandel";

string fullName = string.Format("{0} {1}", firstName, lastName);

Declare Strings with var in C# 3.0

In terms of strings, nothing has changed in C# 3.0. However, you can now declare and initialise local string variables with the var keyword. The type of the variable is inferred implicitly from the assigned value, which in this case is a string:

var firstname = "Niki";

String Interpolation in C# 6.0

Microsoft added string interpolation to C# 6.0. This facilitates the use of C# variables and expressions within a string. Prior to C# 6.0, you had to either concatenate strings with the + character or use the string. Format method as described in this blog post.

String interpolation is available in C# since version 6.0. An interpolated string begins with a $ sign and can include C# variables and expressions by using {and}. The following fullName variable initialization demonstrates this, and it also results in the string Niki Tandel:

var firstName = "Niki";
var lastName = "Tandel";

var fullName = $"{firstName} {lastName}";

Expressions with string interpolation can be used instead of simple variables. The + operator is used in the expression of an interpolated string to add two numbers. The string 2+3=5 will be stored in the variable task.

int num1 = 2;
int num2 = 3;

var task = $"{num1}+{num2}={num1 + num2}"; // Results in the string "2+3=5"

String interpolation, of course, works with both quoted string literals and verbatim string literals. To use string interpolation in a verbatim string literal, begin your string with $@”. This is demonstrated in the following snippet:

var username = "Niki";
            
var folderPath = $@"C:\Users\{username}\Documents";

If you want to use curlies in your quoted or verbatim string literal that uses string interpolation, things get a little more complicated. Because, with string interpolation, curlies in your string are now used for C# variables and expressions. If you want a curly in your output string, you define two curlies in the string literal. Assume you want to define the string Hello Niki when using string interpolation. You do it as shown below. In this snippet, take note of the two curlies that open and close around the word Hello:

var username = "Niki";

var welcomeMessage = $"{{Hello}} {username}"; // {Hello} Niki

The Drawback of Quoted and Verbatim String Literals

There are some drawbacks to using quoted and verbatim string literals. The most significant, in my opinion, is that you can never write your string in code exactly as it appears in the output if it contains special characters such as double quotes. This means you can’t just copy and paste a string into the code editor, like the JSON below:

{
    "firstName":"Niki",
    "lastName":"Tandel"
}

When storing this JSON string with a quoted string literal, including the linebreaks, write it like this:

var json = "{\r\n   \"firstName\":\"Niki\",\r\n    \"lastName\":\"Tandel\"\r\n}";

When using the json string with a verbatim string literal, you must write it as follows:

var json = @"{
    ""firstName"":""Niki"",
    ""lastName"":""Tandel""
}";

The literal string literal is quite close, but as shown in the code snippet above, you must still double each double quote.

When you use multiple lines, the verbatim string literal also includes all of the whitespace on the left. If you don’t want all that whitespace, you must write your string lines on the left side of the source file. This issue becomes more apparent when your code contains nesting. There is a verbatim string literal inside of a method that is inside of a class that is inside of a namespace in the following snippet. The lines of the verbatim string literal are on the left, so the JSON string looks exactly like the one defined in the snippet at the start of this section.

namespace MyNamespace
{
    public class MyClass
    {
        public string GetJson()
        {
            var json = @"{
              ""firstName"":""Niki"",
              ""lastName"":""Tandel""
            }";
         return json;
        }
    }
}

All of the drawbacks of quoted and verbatim string literals are now addressed by raw string literals, a new feature of C# 11.0. Let’s get started.

Raw String Literals in C# 11.0

A raw string literal is a type of string literal that is new. It allows you to write strings exactly how you want them to be stored. This means you can copy and paste any string and use it without modifying it with any escape sequences. The raw strings can be used in your code.

How does this work?

A raw string literal begins with at least three double quotes and ends with the same number. The following snippet demonstrates the three string literal types, all of which define the string Niki:

// Quoted string literal
var firstname1 = "Niki";

// Verbatim string literal
var firstname2 = @"Niki";

// Raw string literal
var firstName3 = """Niki""";

Of course, for such a simple string devoid of special characters, there is no need to use a raw string literal; instead, the quoted string literal is the best option. Before we move on, I’d like to show you one more thing about raw string literals.

Normally, a line break is placed after the three double quotes that begin the string and another before the three double quotes that end the string. This is demonstrated in the code snippet below. These linebreaks are not present in the final string. In addition, the whitespace on the left has been removed. The closing’s horizontal starting position “”” specifies the location of whitespace removal for all lines above. The string Niki is horizontally exactly above the closing “” in the following snippet “.This means that the whitespace to Niki’s left is not part of the string. This also means that both variables in the codesnippet below contain the same string, which is Niki. Note how the linebreaks at the beginning and end of the raw string literal are removed in this case, as well as the white space on the left.

// Quoted string literal
var firstname1 = "Niki";

// Raw string literal
var firstName2 = """
    Niki
    """;

Assume you want to define the string Hello “Niki”. See how you can use that string exactly as it is with the raw string literal in the snippet below:

// Quoted string literal
var welcome1 = "Hello \"Niki\"";

// Verbatim string literal
var welcome2 = @"Hello ""Niki""";

// Raw string literal
var welcome3 = """
    Hello "Niki"
    """;

Using more double quotes

Let’s say you want to make a string with three double quotes in a row, like this: Hello “””Niki”””. The rule is that your raw string literal must have at least one more double quote than the content. Because the content already contains three double quotes, your raw string literal must begin and end with at least four double quotes:

var firstName = """"
    Hello """Niki"""
    """";

I mean, you could add many more double quotes to begin and end your raw string literal, as shown below, and that’s still valid code, but just one more than the content is sufficient as long as you’re not paid by the number of double quotes in your code:

var firstName = """""""
    Hello """Niki"""
    """""""; // You could start and end here with just 4 double quotes

String interpolation with Raw String literals

String interpolation is also supported by raw string literals. As with quoted and verbatim string literals, the $ sign is used. Here’s an example of how to make the string Hello “Niki”:

var firstName = "Niki";

var welcome = $"""
    Hello "{firstName}"
    """; // Hello "Niki"

What if you wanted to make the string {Hello} “Niki”? This indicates that your raw string contains curlies. How does the C# compiler determine whether those curlies begin a C# variable/expression or are part of the content? Raw string literals have a solution for this as well. You can use two $$ signs, and then use within the string you need to use {{ }} to include a C# variable/expression. A single {and} is then interpreted as content. The string {Hello} “Niki” is defined in the following snippet. Take note of the two $$ at the start, as well as the two {{and}} used to use the firstName variable in the interpolated string.

var firstName = "Niki";

var welcome = $$"""
    {Hello} "{{firstName}}"
    """; // {Hello} "Niki"

Now, the same rules apply to curlies as they do to double quotes. In your raw string, you should use one more $ sign than there are curlies in a row. Assume you want to define the string {{{Hello}}} “Niki” using an interpolated string. You need four $$$$ and four {{{{ to begin the C# expression, as the content already contains three {{{ in a row. This is demonstrated in the following snippet:

var welcome = $$$$"""
    {{{Hello}}} "{{{{firstName}}}}"
    """; // {{{Hello}}} "Niki"

Let’s Look at the JSON

As an example, we already had the following small JSON document:

{
    "firstName":"Niki",
    "lastName":"Tandel"
}

You can define it with a raw string literal as shown below, and the JSON in the C# code looks exactly like the JSON that you want to store in the string variable. Nothing in this string needs to be escaped.

var json = """
    {
        "firstName":"Niki",
        "lastName":"Tandel"
    }
    """;

Because the JSON document contains curlies, you must use two $$ signs to use string interpolation in this JSON. This means you begin your C# variables and expressions with {{and end them with  }}. This is demonstrated in the following snippet:

var firstName = "Niki";
var lastName = "Tandel";

var json = $$"""
    {
        "firstName":"{{firstName}}",
        "lastName":"{{lastName}}"
    }
    """;

As previously stated, the closing double quotes of a raw string literal define the horizontal position from which all white space for the preceding lines is removed.

This means that you must place the entire content of your raw string literal either exactly above the closing double quotes or slightly to the right. If your string lines are further left than the closing double quotes, the code editor will report an error.

This whitespace feature means that, unlike with verbatim string literals, you no longer need to move your multi-line strings to the left side of the code file to get the expected whitespace. Examine the following verbatim string literal (which you already saw in this blog post), where everything is on the left, so that the json string does not contain unintended whitespace on the left:

namespace MyNamespace
{
    public class MyClass
    {
        public string GetJson()
        {
            var json = @"{
              ""firstName"":""Niki"",
              ""lastName"":""Tandel""
                 }";
        return json;
        }
    }
}

Because you can’t indent the multi-line verbatim string literal into the GetJson method, the string would contain all of the whitespace on the left in the snippet above.

As previously stated, the closing double quotes in raw string literals define the horizontal position from which the whitespace for the multi-line string begins. This means you can write that GetJson method nicely indented like below, and the JSON will look exactly how you want it in the output, with no doubled double quotes required as with the verbatim string literal:

namespace MyNamespace
{
    public class MyClass
    {
        public string GetJson()
        {
            var json = """
                {
                    "firstName":"Niki",
                    "lastName":"Tandel"
                }
                """;

            return json;
        }
    }
}

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories