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

March 5, 2020
Tom Deseyn
Related topics:
.NET

    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

    • 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

    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.