Raw String Literals - New Feature In C#11 With .NET 7

Introduction

Microsoft released .NET 7 on 14th November 2022 with C#11. We will look at string literals features of C# 11 in this article. Let us begin.

Raw string literals

Let us create a console application using Visual Studio 2022.

New Feature in c#11 with .NET 7 - Raw string literals

New Feature in c#11 with .NET 7 - Raw string literals

Now, add the below code to the Program.cs file for various test scenarios,

// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

//Double Quote 
string quotedXMLValue = """<?xml version = "1.0"?>""";
Console.WriteLine(quotedXMLValue);

//Multiline Message
string multilineMessage = """
   This is a long message.
   It has several lines.
   Some are indented
        more than others.
   Some should start at the first column.
   Some have "quoted text" in them.
   """;
Console.WriteLine(multilineMessage);

//Dynamic Value in string
string name = "Sachchi";
string nameValie = $"""Welcome {name} !!! """;
Console.WriteLine(nameValie);

//Multiple $ characters
double Longitude = -77.0364;
double Latitude = 38.8951;
string location = $$"""You are at {{{Longitude}}, {{Latitude}}}""";
Console.WriteLine(location);

Now run the application and you will see the below output,

New Feature in c#11 with .NET 7 - Raw string literals

In .NET 7 with C#11 simply, adding three quotes makes the string useable. This simplifies the handling of XML and JSON-type strings.

Summary

In this article, we looked at a new feature that has been introduced with .NET 7 along with C# 11. This makes JSON and XML string literals more readable and easier to understand in the code.