Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions

- 30.03.26 - ErcanOPAK

🛡️ No More NullReferenceException

NullReferenceException killing your app? Can’t tell if variable can be null? Nullable reference types (C# 8+) make nullability explicit. Compiler warns about potential null errors.

The Null Problem

// Before nullable reference types
public class UserService
{
    public string GetUserName(int userId)
    {
        var user = _repository.GetById(userId);  // Could return null!
        return user.Name;  // 💥 NullReferenceException if user is null
    }
}

// No compiler warning!
// Crashes at runtime
// "The billion dollar mistake" - Tony Hoare

Enable Nullable Reference Types



  
    net8.0
    enable  
  



#nullable enable  // At top of .cs file
// After enabling nullable reference types
public class UserService
{
    // Non-nullable: Must never be null
    public string GetUserName(int userId)
    {
        User? user = _repository.GetById(userId);  // User? = nullable
        return user.Name;  // ⚠️ Compiler warning: Possible null reference
    }
    
    // Fixed version
    public string GetUserName(int userId)
    {
        User? user = _repository.GetById(userId);
        
        if (user == null)
        {
            throw new UserNotFoundException(userId);
        }
        
        return user.Name;  // ✅ No warning - null checked
    }
    
    // Or return nullable
    public string? GetUserName(int userId)
    {
        User? user = _repository.GetById(userId);
        return user?.Name;  // ✅ Returns null if user is null
    }
}

🎯 Nullable Syntax

// Non-nullable reference type (default)
string name = "Alice";
name = null;  // ⚠️ Warning: Cannot assign null

// Nullable reference type (explicit ?)
string? name = null;  // ✅ OK
name = "Alice";      // ✅ OK

// Non-nullable in method signatures
public void ProcessUser(User user)  // user cannot be null
{
    Console.WriteLine(user.Name);  // ✅ No null check needed
}

// Nullable in method signatures
public void ProcessUser(User? user)  // user might be null
{
    if (user != null)
    {
        Console.WriteLine(user.Name);  // ✅ Null checked
    }
}

// Return types
public User GetUser(int id)      // Never returns null
public User? FindUser(int id)    // Might return null

Null-Handling Patterns

User? user = FindUser(123);

// 1. Null check
if (user != null)
{
    Console.WriteLine(user.Name);
}

// 2. Null-conditional operator
Console.WriteLine(user?.Name);  // Returns null if user is null

// 3. Null-coalescing operator
string name = user?.Name ?? "Unknown";

// 4. Throw if null
User nonNullUser = user ?? throw new ArgumentNullException(nameof(user));

// 5. Pattern matching
if (user is { Name: var name })
{
    Console.WriteLine(name);  // user is not null here
}

// 6. Null-forgiving operator (! - use sparingly!)
Console.WriteLine(user!.Name);  // Tell compiler: "I know it's not null"
// Use only when you're 100% sure

Constructor and Property Initialization

public class User
{
    // ⚠️ Warning: Non-nullable property must be initialized
    public string Name { get; set; }
    
    // ✅ Fixed: Initialize in constructor
    public User(string name)
    {
        Name = name;
    }
}

// Or use required (C# 11)
public class User
{
    public required string Name { get; set; }
    public string? Email { get; set; }  // Optional, can be null
}

var user = new User { Name = "Alice" };  // ✅ OK
var user2 = new User { Email = "test@example.com" };  // ⚠️ Error: Name required

// Or default value
public class User
{
    public string Name { get; set; } = string.Empty;
    public List Orders { get; set; } = new();
}

🔧 Suppress Warnings (When Needed)

// Null-forgiving operator !
string GetName(User? user)
{
    // You KNOW user is not null (e.g., validated earlier)
    return user!.Name;  // Suppresses warning
}

// Pragma directive (suppress for block)
#pragma warning disable CS8600  // Converting null literal
string? name = null;
#pragma warning restore CS8600

// Attribute (for methods that ensure non-null)
public static bool TryGetUser(int id, [NotNullWhen(true)] out User? user)
{
    user = FindUser(id);
    return user != null;
}

if (TryGetUser(123, out var user))
{
    Console.WriteLine(user.Name);  // ✅ Compiler knows user is not null
}

✅ Benefits

  • Catch bugs early: At compile-time, not runtime
  • Self-documenting: API clearly shows what can be null
  • Better tooling: IDE shows nullable warnings
  • Safer code: Forces you to handle null cases
  • Fewer crashes: NullReferenceException reduced dramatically

💡 Migration Strategy

  • Enable gradually: Per-file with #nullable enable
  • Start with new code: Don’t rewrite everything at once
  • Fix warnings systematically: Don’t suppress blindly
  • Use analyzers: Enable all nullable warnings
  • Team buy-in: Everyone must understand nullable

🎯 Real-World Example

#nullable enable

public class OrderService
{
    private readonly IOrderRepository _repository;
    private readonly IEmailService _emailService;

    public OrderService(IOrderRepository repository, IEmailService emailService)
    {
        _repository = repository;
        _emailService = emailService;
    }

    // Clear contract: Never returns null
    public Order GetOrder(int id)
    {
        Order? order = _repository.FindById(id);
        
        if (order == null)
        {
            throw new OrderNotFoundException($"Order {id} not found");
        }
        
        return order;  // ✅ Guaranteed non-null
    }

    // Clear contract: Might return null
    public Order? FindOrder(int id)
    {
        return _repository.FindById(id);  // ✅ Nullable return
    }

    public async Task ProcessOrder(Order order, string? promoCode)
    {
        // order is non-nullable - no need to check
        order.Status = OrderStatus.Processing;

        // promoCode is nullable - must check
        if (promoCode != null)
        {
            ApplyPromoCode(order, promoCode);
        }

        await _repository.SaveAsync(order);
        
        // Email might be null, handle gracefully
        await _emailService.SendConfirmationAsync(order.CustomerEmail ?? "no-reply@store.com");
    }
}

“Enabled nullable reference types on legacy codebase. Compiler found 147 potential null bugs. Fixed them all. NullReferenceException crashes dropped 95%. Best decision for code quality.”

— Tech Lead

Related posts:

C#: Save Memory with ValueTask in High-Throughput Scenarios

C#: Save Memory with ValueTask in High-Throughput Scenarios

Constructor for a static class in C#

Constructor for a static class in C#

C#: Use Generic Math for Mathematical Algorithms on Any Numeric Type

C#: Use Generic Math for Mathematical Algorithms on Any Numeric Type

Views: 22

Post navigation

C#: Use Record Types for Immutable Data Objects
C#: Use Expression-Bodied Members for Concise Single-Line Methods

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com