Friday, June 26, 2026

C# Nullable reference types and Operators on Nullable Types

In this post we learn about:
  • Nullable reference types
  • Non-nullable reference types
Nullable reference types: They may have null value and they are declared similar to nullable value types by using nullable annotation(?) after data type.
Example
string? FirstName;
They must be initialized before using it.
string? FirstName = null;

Non-nullable reference types: They must be assigned a non-null value at initialization and cannot be later changed to a null value.
Example
string Name = String.Empty;

Enabling Nullable reference types Feature in Visual Studio
You can enable/disable nullable reference type features in project file using enable/disable/warning values. The current settings uses enable value:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>True</AllowUnsafeBlocks>
  </PropertyGroup>

</Project>

Operating on Nullable Types
C# provides several operators for working with nullable types. They are
  • the null-coalescing operator, 
  • the null-coalescing assignment operator, and 
  • the null conditional operator.

The null-coalescing operator
Look at the following code. The null-coalescing operator(??) returns the second operand if first operand is null else it returns the first operand.

string? FirstName = null;
var result = FirstName ?? ThisValueIfFirstNameIsNull;

Example of traditional approach would be:
class Test
{
    public string? FirstName = null;
    string result = string.Empty;
    public string GetName()
    {
        if (FirstName != null)
        {
            result = FirstName;
        }
        else
        {
            result = "ThisValueIfFirstNameIsNull";
        }
        return result;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        test.FirstName = "Ajeet";
        Console.WriteLine(test.GetName());
        test.FirstName = null;
        Console.WriteLine(test.GetName());
    }
}
The  null-coalescing operator(??) provides concise solution for the same:
class Test
{
    public string? FirstName = null;
    string result = string.Empty;
    public string GetName()
    {
        return FirstName ?? "ThisValueIfFirstNameIsNull";
    }
}
class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        test.FirstName = "Ajeet";
        Console.WriteLine(test.GetName());
        test.FirstName = null;
        Console.WriteLine(test.GetName());
    }
}
The null-coalescing assignment operator
Look at the following code. The null-coalescing assignment operator(??) assigns the second operand to first one if first operand is null and then returns else it simply returns the first operand.

string? FirstName = null;
FirstName ??= ThisValueIfFirstNameIsNull;

Example of traditional Approach would be:
class Test
{
    public string? FirstName = null;
    public string GetName()
    {
        if (FirstName != null)
        {
            return FirstName;
        }
        else
        {
            return "ThisValueIfFirstNameIsNull";
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        test.FirstName = "Ajeet";
        Console.WriteLine(test.GetName());
        test.FirstName = null;
        Console.WriteLine(test.GetName());
    }
}
The  null-coalescing assignment operator(??=) provides concise solution for the same:
class Test
{
    public string? FirstName = null;
    public string GetName()
    {
        return FirstName ??= "ThisValueIfFirstNameIsNull";
    }
}
class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        test.FirstName = "Ajeet";
        Console.WriteLine(test.GetName());
        test.FirstName = null;
        Console.WriteLine(test.GetName());
    }
}
The null-coalescing assignment operator
The null conditional operator(?.) evaluates the expression if first expression is not null else it ignores the expression:

expression1?.expression2
  • The expression2 is generally a property or method of an object.
  • The null conditional operator(?.) helps to avoid null reference exception at runtime.
Example
class Test
{
    public int? GetLength(string? name)
    {
        return name?.Length; // possiibility of NullReferenceException without ?.
    }
}
class Program
{
    string? first = null;
    string? last = "Kumar";
    int? result;
    static void Main(string[] args)
    {
        Program obj = new Program();
        Test test = new Test();
        obj.result = test.GetLength(obj.first);
        obj.result = test.GetLength(obj.last);
        Console.WriteLine(obj.result);
    }
}

No comments:

Post a Comment

Hot Topics