Skip to main content
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 Red Hat 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

    • Red Hat OpenShift AI
    • 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.

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

    • 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.

ConsoleDocsSupport Search
New For you

Recommended

We'll recommend resources you may like as you browse. Try these suggestions for now.

  • Product downloads
  • Cheat sheets
  • Red Hat Developer learning portal
  • Developer blog
  • E-books
  • Developer Sandbox
Log in

Get more with a Red Hat Developer account

  • Product downloads
  • Console access
  • Event registration
  • Training & trials
Explore more account benefitsLog in or register

A subscription may be required for some services.

Contact us

Some more C# 11

January 11, 2023
Tom Deseyn
Related topics:
.NET
Related products:
Red Hat Enterprise Linux

    This is the final article in our series about C# 11. You might not use the features in this article often in your own code, but you will definitely see them in library source code and code generated by source generators. In this article, we will discuss five new advanced features: UTF-8 string literals, file-scoped types, extended nameof support, generic attributes, and ref fields.

    Follow the C# 11 series:

    • Part 1: Raw strings, required members, and auto-default structs
    • Part 2: Pattern matching and static abstract interfaces

    UTF-8 string literals

    .NET uses UTF-16 encoding for the string type. Often, strings are actually stored and transferred as UTF-8 because that encoding requires fewer bytes.

    C# 11 allows you to directly create the UTF-8 representation of a literal string by adding the u8 suffix:

    ReadOnlySpan<byte> HttpGet = "GET"u8;

    Previously, converting such literal strings to UTF-8 required either manually creating the corresponding byte array (or better, using a source generator) or using the Encoding.UTF8 class and paying a run-time cost.

    This feature is interesting for libraries that implement protocols, such as ASP.NET Core.

    File-scoped types

    While implementing a type, you might want to move some logic into helper classes. Previously, such classes needed to be named or scoped in a way that would not conflict with other classes.

    C# 11 enables types declared with file scope. These types won't be visible to any other files in the project. You'll see source-generators use this scope for internal helper types that are not meant to be used directly. Thanks to the file scope there can't be any name conflicts with other types defined or referenced by the project.

    The following example shows a Console class that is visible only in the .cs file that contains it and doesn't cause name conflicts with System.Console in the rest of the project.

    // Calls into the 'Console' class that is defined in this file.
    Console.WriteLine("Hello, World!");
    
    // This 'Console' class is not visible to other files.
    file static class Console
    {
       public static void WriteLine(string s) => System.Console.WriteLine(s);
    }

    Extended nameof

    The nameof operator provides a convenient way to turn identifiers into strings.

    C# 11 allows you to use parameter types and parameter names with nameof in method attributes. In previous versions, these identifiers were out of scope.

    The following example shows how the NotNullIfNotNullAttribute attribute can be used to indicate that the method doesn't return null when the path argument is not null.

    [return: NotNullIfNotNull(nameof(path))]
    public static string? GetExtension(string? path)

    Generic attributes

    Previously, attributes could use types by directly using the Type class as a constructor argument or property. In C# 11, types can be used as generic attributes:

    [MyAttribute<int>]
    void Foo() { }
    
    class MyAttribute<T> : Attribute { }

    This enables a nicer syntax. The type specified as the argument must be fully known at compile time.

    ref fields

    The ref keyword indicates that a variable is passed by reference. Passing a variable by reference enables the called function to change the value of the variable in the calling function.

    C# supports ref on a method argument or method return, as well as on a local variable:

    int i = 10;
    
    Foo(ref i);
    
    ref int Foo(ref int j)
    {
       ref int k = ref i;
       return ref j;
    }

    In this example, the parameter j and local k are aliases for int i. When you get their values i is read, and when you set their values i is set. The compiler guards the scope. For example, you are allowed to return ref j because the compiler knows that the variable referred to by the parameter will still be in scope. The compiler would not allow you to return ref k because the local ref could point to stack memory that goes out of scope when the method returns.

    As we've just covered, ref variables can point to stack memory, which implies strict scoping rules. ref variables can also point to heap memory, which is managed by the garbage collector (GC). Like variables that have reference types, the GC tracks ref variables.

    C# 8 (.NET Core 2.1) introduced ref struct and used it to implement Span. The Span type is an abstraction for memory that is on either the stack or the heap. A ref struct can live only on the stack.

    To represent memory, Span needs two fields: a ref field that points to the first element of the memory and a length field to store the length of the memory.

    In previous versions of .NET, the Span implementation was handled internally by the runtime.

    C# 11 introduces ref fields as a first-class language concept. This construct lets you describe your Span type and define your own ref structs that have ref fields. For example, you can create a type that is used to read information from a large struct that can be on the stack, be on the heap, or even be unmanaged memory:

    struct MyStruct { /* large struct */}
    
    ref struct MyStructReader
    {
       ref MyStruct _value;
       public MyStructReader(ref MyStruct value) => _value = ref value;
       ...
    }

    When you pass references to methods on a ref struct, the compiler ensures that the variables you refer to don't go out of scope before the struct itself. Otherwise, the ref struct might refer to out-of-scope variables:

    void Process(ref MyStructReader reader)
    {
       Span<byte> buffer = stackalloc byte[10];
    
       // error CS8352: Cannot use variable 'buffer' in this context because it may expose referenced variables outside of their declaration scope
       reader.ReadSomeValue(buffer);
       ...
    }

    You can tell the compiler to allow these variables to be passed in by adding the scoped keyword. The compiler then disallows storing these parameters in the struct:

    ref struct MyStructReader
    {
       ...
       public void ReadSomeValue(scoped Span<byte> value) { ... }
       ...

    In other words, scoped tells the compiler to treat the argument with the same scope as a local variable in the method.

    By default, this is a scoped ref. That definition makes it impossible to return references to its fields. To overcome that limitation, we can add the opposite of the scoped keyword: the UnscopedRef Attribute:

    ref struct MyStructBuilder
    {
       MyStruct _value;
    
       [UnscopedRef]
       ref MyStruct Value { get { EnsureInitialized(); return ref _value; } }
       ...

    The C# 11 series concludes

    In this final article of our C# 11 series, we looked at UTF-8 string literals, file-scoped types, extended nameof support, generic attributes, and ref fields. These new features improve C# for specific use cases.

    We hope you have found this C# 11 series beneficial. As always, we welcome your feedback.

    Last updated: December 10, 2023

    Related Posts

    • Use Kebechet machine learning to perform source code operations

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

    • C# 11: Pattern matching and static abstract interfaces

    • Three ways to containerize .NET applications on Red Hat OpenShift

    Recent Posts

    • A day in the life of an NVIDIA H100 on Red Hat OpenShift 5

    • Migrate BuildConfigs to builds for Red Hat OpenShift with one plug-in install

    • Run Red Hat Enterprise Linux CoreOS on NVIDIA BlueField DPUs

    • Agent harness engineering: Separating model capabilities from enforcement

    • What's new for developers in Red Hat Enterprise Linux 10.3 and 9.9

    What’s up next?

    Learn how to deploy a full-stack JavaScript application in an OpenShift cluster with this hands-on lab. Starting from source code, you'll take an application that runs locally and deploy it in the Developer Sandbox for Red Hat OpenShift.

    Get started
    Red Hat Developers logo

    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
    Ask AI