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# 8 nullable reference types

March 5, 2020
Tom Deseyn
Related topics:
.NET

Share:

    In the previous article, we discussed C# 8 default interface methods. In this article, we’ll look at C# 8 nullable reference types. Reference types refer to an object that is on the heap. When there is no object to refer to, the value is null. Sometimes null is an acceptable value, but often it is an illegal value that leads to ArgumentNullExceptions and NullReferenceExceptions.

    C# 8 finally gives us the ability to express whether a variable shouldn’t be null, and when it can be null. Based on these annotations, the compiler will warn you when you are potentially using a null reference, or passing a null reference to a function that won’t accept it.

    To enable the feature, you must add the following line in the project file (csproj) PropertyGroup:

    <Nullable>enable</Nullable>
    

    Other values than enable are possible and make the compiler a bit more relaxed. It’s also possible to change this setting per file. See the nullable context documentation for more information.

    The ? character is used to indicate when a type might be null. When the ? character is not present, the type is assumed to be non-nullable:

    MyClass? mayBeNull = null;
    MyClass  mayNotBeNull = new MyClass();
    

    We can also use this syntax for method arguments and return values:

    static MyClass Foo(MyClass? mayBeNull)
    {
        return mayBeNull ?? new MyClass();
    }
    

    The method Foo accepts an argument that might be null, and returns an argument that is not.

    The compiler doesn’t just rely on the type declaration. It also follows the code paths to understand when a type will no longer be null:

    static void Bar(MyClass? arg)
    {
        if (arg == null)
        {
            throw new ArgumentNullException(nameof(arg));
        }
    
        arg.Method();
    }
    

    In this example, the compiler understands that arg cannot be null when we call arg.Method since we’ve thrown for that earlier. If we leave out the null check, then we get a warning for the arg.Method call:

    CS8602: Dereference of a possibly null reference.

    Suppose that we had accidentally missed typing the throw keyword. In that case, we would also get that warning.

    There might be cases where the compiler doesn’t understand that a variable can no longer be null. For example, if your class allows one method to only be called in a state where you are sure that a field has already been set. We can pass this information to the compiler using the null-forgiving operator (!):

    string scheme = _uri!.Scheme; // _uri is of type Uri?
    int port = _uri.Port;
    

    Because we used the ! operator on the variable, the compiler knows it's safe. We don't need to use the null-forgiving operator on the next line when we access Port. The compiler infers that _uri can no longer be null.

    The nullable annotations added to the method argument become part of the assembly as Attributes. .NET Core base libraries are being updated to include these annotations.

    The compiler inspects within a method. When the method has strong guarantees regarding how it behaves for nullable arguments, the method can be augmented with Attributes that express this:

    static void Bar(MyClass? arg)
    {
        if (arg == null)
        {
            ThrowArgumentNull(nameof(arg));
        }
    
        arg.Method();
    }
    
    [DoesNotReturn]
    public static void ThrowArgumentNull(string paramName)
    {
        throw new ArgumentNullException(paramName);
    }
    

    In this simple example, we use the DoesNotReturn attribute, which tells the compiler that arg won’t be null past the if block because ThrowArgumentNull never returns. Some attributes can be conditional on values. For example, string.IsNullOrEmpty is annotated as follows:

    public static bool IsNullOrEmpty([NotNullWhenAttribute(false)] string? value)
    

    This annotation makes the compiler understand that the value argument isn’t null when this method returns false.

    You can find these attributes and more in the System.Diagnostics.CodeAnalysis namespace. These attributes are available in .NET Core 3.x (and netstandard2.1).

    Conclusion

    C# 8 provides us with a mechanism to express when a reference type might be null and when it is not. Thanks to these annotations, we can now express the nullability expectations of APIs. The compiler uses this information to provide warnings that could otherwise cause unexpected exceptions at runtime. For more new features, see the last part of our series, Some more C# 8.

    C# 8 can be used with the .NET Core 3.1 SDK, which is available on RHEL, Fedora, Windows, macOS, and other Linux distributions.

    Last updated: February 22, 2024

    Recent Posts

    • What qualifies for Red Hat Developer Subscription for Teams?

    • How to run OpenAI's gpt-oss models locally with RamaLama

    • Using DNS over TLS in OpenShift to secure communications

    • Scaling DeepSeek and Sparse MoE models in vLLM with llm-d

    • Multicluster authentication with Ansible Automation Platform

    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