Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

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

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

    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

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    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

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.