How to trigger nullability check in C#?
12:54 31 Mar 2026

Say, I have this extension which throws exception when `fileName` is null or when file does not exist.

internal static class ExceptionExtensions
{
  extension(FileNotFoundException)
  {
    internal static void ThrowIfNullOrNotExist(string? fileName)
    {
      if (string.IsNullOrWhiteSpace(fileName) || !File.Exists(fileName))
      {
        throw new FileNotFoundException("File has not been found", fileName);
      }
    }
  }
}

However, this does not trigger the nullability check. For instance:

internal static void WriteFile(string? fileName)
{
  FileNotFoundException.ThrowIfNullOrNotExist(fileName);
  
  // Later...
  using var fs = new FileStream(fileName, fso);
}

The editor shows squiggles under fileName:

filename may be null here.

How do I trigger nullability check?

c# nullability