Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

C# 11: Raw strings, required members, and auto-default structs

November 30, 2022
Tom Deseyn
Related topics:
.NET
Related products:
Red Hat Enterprise Linux

Share:

    This article is the first in a series in which we'll look at the new features of C# 11. Released in November of 2022, .NET 7 includes support for C# 11, a new major version of the C# programming language. In this article, we'll look at interpolated strings, required members, and auto-default structs. These features can be used in everyday programs.

    Follow the C# 11 series:

    • Part 1: Raw strings, required members, and auto-default structs
    • Part 2: Pattern matching and static abstract interfaces
    • Part 3: 5 new advanced features improving C# 11

    Raw string literals

    Before we look at the new C# features, let's recap how interpolated strings evolved across C# versions.

    In early C#, adding values in a string was performed using format strings. A format string contains placeholders that are then substituted by values. Methods like string.Format() and Console.WriteLine() support this pattern.

    Console.WriteLine("{0} is {1} years old", person.Name, person.Age);
    

    Because braces are used for placeholders, the string formatter allows adding literal braces by using double braces ({{ or }}) in the format string.

    A backslash is used to add quotes and other special characters like newlines into the string (\n, \, \\).

    To avoid backslash-escaping, C# also supports verbatim strings using the @" specifier. All characters are treated literally (including newlines). Quotes can be added using double quotes.

    string s =
    @"The paths are:
    {""C:\dir1"",
    ""C:\dir2""}";
    

    With C# 6 (.NET 4.6), string interpolation became a language feature using the $” specifier.

    Console.WriteLine($"{person.Name} is {person.Age} years old");
    

    As with format strings, double braces must be used to add literal braces to the string.

    Since .NET 6, such interpolated strings are handled very efficiently by the compiler and avoid boxing and allocations that take place when using the Format methods (which take their values as an object array).

    Interpolated strings didn't allow the use of newlines in their expressions. Because these expressions are regular C#, this was an artificial limitation that has been removed in C# 11.

    // C# 11 allows using newlines in interpolated string expressions.
    Console.WriteLine($"The first person is {people.OrderBy(s => s.Name)
                                                   .First()}");

    Interpolated strings can be combined with verbatim strings, like so:

    string paths =
    $@"The paths are:
    {{""C:\{dir1}"",
    ""C:\{dir2}""}}";

    As with regular interpolated strings, literal braces need to be escaped as double braces.

    As shown in the previous example, in .NET 6 we were still required to escape quotes and braces. These characters are common in data formats like JSON and XML. C# 11 introduces raw string literals, which enable the use of these data formats directly without any escaping.

    string json= """
       {
           name: "John",
           age: 49
       }
       """;

    A raw literal string starts with three or more quote characters, and it is terminated by the same number of quotes on a line. Anything appearing inside the string with fewer quotes is verbatim, like the quotes surrounding "John".

    In this string, the newline after the starting quotes and the newline before the ending quotes are not considered part of the string. The indentation before the ending quotes is discarded over all lines.

    Raw literal strings can be interpolated by prefixing with a $. As with the quotes, the number of dollar signs can be changed to control the number of braces needed for an expression. Fewer braces appear verbatim in the output.

    string json= $$"""
       {
           name: {{name}},
           age: {{age}}
       }
       """;

    In this example, we've used two dollar signs to make the single braces appear literal and to use double braces for interpolated expressions.

    Required members

    C# 9 introduced init accessors to create immutable objects. Unlike a set accessor, the init accessor can only be used while constructing the object.

    class Person
    {
       public string Name { get; init; }
       public DateTime BirthDay { get; init; }
    }
    
    Person john = new Person { Name = "John", BirthDay = new DateTime(1970, 4, 1) };
    
    john.BirthDay = DateTime.Now; // error: can only be assigned in object initializer

    If you have nullable enabled for your project, the compiler will give a warning for this code:

    Non-nullable property 'Name' must contain a non-null value when exiting constructor.

    To get rid of the warning, we could add a constructor that accepts the name as an argument. However, that would force us to use a different syntax for initializing the object. Another option is to initialize the property with null!.

    public string Name { get; init; } = null!;
    

    This silences the nullable warning without fixing it.

    C# 11 gives us a new option: we can mark properties (and fields) as required.

    class Person
    {
      public required string Name { get; init; }
      public DateTime BirthDay { get; init; }
    }
    
    var person = new Person() { Name = "John" };

    The compiler will require all required members to be set in the object initializer. If we leave out Name from the initializer, we'll get an error.

    If the type also has a constructor, the compiler will still require that these members be added to the initializer. You can tell the compiler this is not needed by marking the constructor with the SetRequiredMembers attribute (from System.Diagnostics.CodeAnalysis).

    class Person
    {
      public required string Name { get; init; }
      public DateTime BirthDay { get; init; }
    
      [SetsRequiredMembers]
      public Person(string name) => Name = name;
    }

    The compiler uses this attribute when analyzing the call to the constructor. It doesn't verify that the constructor actually initializes the members. This is similar to other analyses (like when tracking nullable).

    Auto-default structs

    In previous versions of C#, when you add a constructor to a struct, the compiler requires you to initialize all fields. Consider the following example:

    struct MyStruct
    {
       private int _field;
    
       public MyStruct()
       { }
    }

    This would give an error because _field is not initialized in the constructor. C# 11 no longer requires this: all fields that are not initialized in the constructor will be set to their default value.

    Note that this example uses a parameterless constructor. This is a constructor that C# supports in C# 10 and all subsequent versions of the language. Before that, all user-defined constructors required arguments, and the default constructor would always initialize all fields to default. Auto-default fields apply to all constructors.

    Conclusion

    In this first article on C# 11, we looked at raw string literals, required members, and auto-default structs. You'll find these new features useful in your everyday C# development. The next article describes two features: pattern matching and static abstract interfaces and how they enable generic math.

    Last updated: January 10, 2023

    Related Posts

    • .NET 7 now available for RHEL and OpenShift

    Recent Posts

    • Why some agentic AI developers are moving code from Python to Rust

    • Confidential VMs: The core of confidential containers

    • Benchmarking with GuideLLM in air-gapped OpenShift clusters

    • Run Qwen3-Next on vLLM with Red Hat AI: A step-by-step guide

    • How to implement observability with Python and Llama Stack

    What’s up next?

    Ready to level up your Linux knowledge? Our Intermediate Linux Cheat Sheet presents a collection of Linux commands and executables for developers and system administrators who want to move beyond the basics.

    Get the free cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue