0
0
CsharpHow-ToBeginner · 3 min read

How to Enable Nullable Reference Types in C#

Enable nullable reference types in C# by adding <Nullable>enable</Nullable> in your project file (.csproj) or by adding #nullable enable at the top of your C# source files. This feature helps the compiler warn you about possible null reference errors.
📐

Syntax

To enable nullable reference types, you can use either the project file setting or the source code directive.

  • Project file (.csproj): Add <Nullable>enable</Nullable> inside a <PropertyGroup>.
  • Source code: Add #nullable enable at the top of your C# file.

Once enabled, you can use string? to declare a string that can be null, and string to declare a string that cannot be null.

xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>
💻

Example

This example shows how nullable reference types work after enabling them. The compiler warns if you assign null to a non-nullable string.

csharp
#nullable enable
using System;

class Program
{
    static void Main()
    {
        string nonNullable = "Hello";
        string? nullable = null;

        Console.WriteLine(nonNullable);
        Console.WriteLine(nullable ?? "Nullable is null");

        // The following line would cause a compiler warning:
        // nonNullable = null;
    }
}
Output
Hello Nullable is null
⚠️

Common Pitfalls

Common mistakes when enabling nullable reference types include:

  • Not enabling the feature in the project or source file, so no warnings appear.
  • Ignoring compiler warnings about possible null assignments.
  • Confusing nullable value types (like int?) with nullable reference types.

Always enable nullable reference types at the project level for consistent behavior.

csharp
/* Wrong: Nullable not enabled, no warnings */
string s = null; // No warning, but risky

/* Right: Nullable enabled, warning shown */
#nullable enable
string s = null; // Warning: Converting null to non-nullable

string? s2 = null; // Allowed, no warning
📊

Quick Reference

SettingDescription
enableEnables nullable reference types project-wide in .csproj
#nullable enableEnables nullable reference types in a single C# source file
stringNon-nullable reference type (default when enabled)
string?Nullable reference type, can be null
Compiler warningsShown when assigning null to non-nullable or dereferencing nullable without checks

Key Takeaways

Enable nullable reference types by adding enable in your .csproj file.
Use #nullable enable at the top of C# files to enable nullable context per file.
Declare nullable references with a question mark, e.g., string?, to allow null values.
Pay attention to compiler warnings to avoid null reference exceptions at runtime.
Enabling nullable reference types improves code safety and clarity about nullability.