Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      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
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java 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

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • 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

Some more C# 11

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

Share:

    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

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    • How to update OpenStack Services on OpenShift

    • How to integrate vLLM inference into your macOS and iOS apps

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

    Red Hat legal and privacy links

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

    Report a website issue