The 30-Day .NET Challenge, Day 9: Null Safety

Written by ssukhpinder | Published 2024/03/28
Tech Story Tags: csharp | programming | dotnet | software-development | dotnet-core | coding | oops | csharp-tutorial

TLDRThis article demonstrates the use of null-state analysis to remove compiler warnings of “check code for null safety’ C# developers often face the System.NullReferenceException, which happens when a null is referenced at runtime, which results in the most common exception in the.NET application.via the TL;DR App

Introduction

The article demonstrates the use of null-state analysis to remove compiler warnings of “check code for null safety”.

Learning Objectives

Discover how to set up the nullable context in your C# project or codebase.

Prerequisites for Developers

  • Familiarity with introductory-level C# programming
  • Know how to use Visual Studio Code or Visual Studio
  • .NET SDK version 6.0 or newer

Getting Started

.NET developers often face the System.NullReferenceException, which happens when a null is referenced at runtime and results in the most common exception in the .NET application.

As the creator of null, Sir Tony Hoare, refers to null as the "billion-dollar mistake."

Example

The variable records is set to null and then immediately referenced which results in System.NullReferenceException

    TestRecord records = null;
    
    _ = records.ToString();
    
    record TestRecord(int Id, string Name);

As the applications grow in the number of lines of code and become more complex, spotting such issues as a developer can be challenging.

This is where C# compiler steps in.

Define null safety

In the previous example, a developer can avoid the System.NullReferenceExceptionby checking if the records variable was null as shown below.

    TestRecord records = null;
    
    // Check for null
    if (records is not null)
    {
        _ = records.ToString();
    }
    
    record TestRecord(int Id, string Name);

Nullable Types

The default value for all reference types is null.

    string first;                  // first is null
    string second = string.Empty   // second is not null, instead it's an empty string ""
    int third;                     // third is 0 because int is a value type
    DateTime date;                 // date is DateTime.MinValue

In the example mentioned earlier:

  • The variable “first” is null because a reference type “string” was declared but not assigned any value.
  • The variable “second” is assigned the value “string.Empty” during declaration.
  • The variable “third” has a value of 0 even though it was not explicitly assigned.
  • The variable “date” is uninitialized, but its default value is “System.DateTime.MinValue.”

Post C# 2.0 version, we can define nullable values using Nullable<T>. This allowed value types to be assigned with a value of null.

    int? first;            // first is implicitly null (uninitialized)
    int? second = null;    // second is explicitly null
    int? third = default;  // third is null as the default value for Nullable<Int32> is null
    int? fourth = new();    // fourth is 0, since new calls the nullable constructor

Nullable context

As per my experience, this is a must-have feature that should be enabled in every .Net application as it enables control for how the compiler understands reference type variables.

There are four types of nullable contexts

  • disable
  • enable
  • warnings
  • annotations

Enable nullable context

it can be enabled by adding <Nullable> item to the <PropertyGroup> inside the application .csproj file as shown below

    <Project Sdk="Microsoft.NET.Sdk">
    
        <PropertyGroup>
            <OutputType>Exe</OutputType>
            <TargetFramework>net6.0</TargetFramework>
            <Nullable>enable</Nullable>
        </PropertyGroup>
    
        <!-- Omitted for brevity -->
    
    </Project>

Alternatively, developers can also add scope nullable context which means the nullable context will be applicable only in the defined scope.

    #nullable enable

Complete Code on GitHub

GitHub — ssukhpinder/30DayChallenge.Net

C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

If you’ve made it this far, please show your appreciation with a clap and follow the author! 👏️️

Follow us: X | LinkedIn | Dev.to | Hashnode | Newsletter | Tumblr

Visit our other platforms: GitHub | Instagram | Tiktok | Quora | Daily.dev

More content at C# Programming


Also published here.


Written by ssukhpinder | Programmer by heart | C# | Python | .Net Core | Xamarin | Angular | AWS
Published by HackerNoon on 2024/03/28