Raw String Literals In C# 11

Introduction

The requirements of developers are changing day by day, which is why each programming language updates its functionalities in its latest version. Now, the latest version of C# is expected to release in November 2022, which is C#11. In this article, I will discuss upcoming features of string that are updated and added in C#11. The availability of these features in the official release depends on the feedback. 

Raw string literals

Raw string literals are used to make coding more efficient and easy. Using a raw string literal, we can make our code more readable and productive. If someone wants to contain JASON, XML, SQL, HTML, or Regex in the string, then this feature will be useful for them. You can easily contain these types of raw data in a string using a raw string literal.

                     We can also print \t, \n, or other escape characters as it is then, it was not possible in the previous version if we put \t or \n then \t is treated as tab space and \n treated as a new line. In the current update by using “””...........””” we can easily contain escape characters and treat them as they are. 

Example

Currently, I’m using Visual Studio 2022 version17.2.5, but version 17.3 is recommended. If someone wants to use these features, they will also need to use Visual Studio 2022 until upcoming versions are released. First, open Visual Studio and click on create a new project.


Figure- Creating a new Project

Next, we need to select the project type as a console app.


Figure-Choosing project type

Now we need to enter the project Name. I'm choosing 'CsharpFeatures' as a project name, but you can choose a project name in your interest.


Figure-Project Name

Then we need to choose the framework. The latest framework is .NET Framework 6.0, but in the future you will be able to choose the other latest versions. Click the next button now to open the program.cs file. Create a Main class to test the new features of C# 11. Before we start, you need to enable C# 11 preview.

How to enable C# 11 preview.

Open Solution Explorer by pressing CTRL+ALT+L. We can also open Solution Explorer by going to  View menu >> Solution Explorer. Then, we must double click on the Project name, which is the CsharpFeatures.csproj file. Next, we need to add this code in this file:

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <LangVersion>preview</LangVersion>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>preview</LangVersion>
</PropertyGroup>

In the following code, we add two PropertyGroups to enable the preview of the language version and debug. Click the save icon or press CTRL+S, and the preview of the latest version will be enabled.

This is the easiest way to enable a preview of the latest version of the language. You just need to write some code or syntax, which is available in the latest version of the language, like what I have just written a declaration of Raw Literal String:

public class Main {
    public void testc() {
        string longMessage = ""
        "hii\ sam "
        "";
    }
}

This will show an error. The reason behind the error is that the preview of the latest language version is not enabled in the project. 


Figure- C#11 Preview Error

We simply need to press CTRL+. We also need to choose this suggestion to upgrade to preview.


Figure- Load Preview version

Simply click enter and the following code will be added automatically to the project file. 

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <LangVersion>preview</LangVersion>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>preview</LangVersion>
</PropertyGroup>

Let's get introduced to the new syntax of the new Raw String literals.

There are three syntaxes 

Syntax 1

string variable_name=""" message or other  escape characters"""";

Explanation

 In this new syntax, we need to type string that represents its type. Second, we have to use """ to start the string, and also use """ to end the string. Usually, you can choose this syntax when you have a small string. Keep in mind that if we start typing a string in the same line where we start """ , then it must end that string in the same line with the """. If this is not done, it will show errors.


Figure-Syntax error in Raw string literals C# 11

To solve this error, you need to end your string with the same line.

string longMessage = """ hii sam """;

Now you can see that the error has been resolved.

Syntax 2

This syntax is useful when you need to use a long string.

string variable_name="""

message or other escape characters

with multiline and / and other things.............

""";

Explanation

In this syntax, we need to type a string that represents a type of string. Second, we use """ and then press enter, and start typing the string in the new line. When your string ends, you need to press enter again and end your string with """ . Otherwise, it will raise a syntax error.

Syntax 3 

data_type another_variable=some value ;

string variable_name=$$""" {{{another_variable}}}""";

Explanation

This syntax is useful when you need to print some variables with their values. You can also use '{}' to specify the value. First, we use string to specify the string type. Second, we need to specify the variable name. Then we must put at least two $$ symbols, then triple """. Then type your message and values. The number of symbols will define the number of {} to escape and print values under them. If I use $$$ symbols, then I can use {{{{value or variable}}}, and the only value will be printed.

Example

Let's write a program that shows these features.

Main obj = new Main();
obj.testc();
public class Main {
    public void testc() {
        string Message1 = ""
        " hii\ sam "
        ""; // single line string with \
        string Message2 = ""
        "
        message or other escape characters
        with multiline and / and other things.............
        ""
        ";//multi line string 
        float Im_Float = 0.2448484 f;
        string Message3 = $$ ""
        "
        It 's a float value Under the string and curly barkets- {{{Im_Float}}}
        ""
        ";// string with values and {}
        Console.WriteLine(Message1);
        Console.WriteLine(Message2);
        Console.WriteLine(Message3);
    }
}

Output


Figure-Raw string Literals Output

Explanation

In this Program first, we have created a class with the name Main you can choose a name of your interest. Then we created a method with the name testc(). In this method, we have performed our testing task of Raw String Literals And in the last, we have called this method by using the object of our class. 

Importance of Raw String Literals in C#11

Raw String Literals are quite useful. We can also treat {} as it is while adding values in the string. We simply need to use double $$ and then can perform it as shown in this article. This feature also supports multiline strings and is capable of holding escape characters. 

Conclusion

In this article, we learned about the new feature of C# 11, Raw String Literal. I'm sure that I will be a great help in optimizing your code, reducing the complexity of your code, and more. It will also be a large help in making your base of programming stronger and speeding up your way to writing the solutions to problems.


Similar Articles