Fix: NullReferenceException from Enum.Equals with a null nullable enum on .NET 11.0.0
A .NET 11.0.0 JIT bug makes enumValue.Equals(nullableEnum) throw NullReferenceException in optimized code when the nullable is null. It breaks iText, Testcontainers.Kafka and Open XML SDK. Fixed in 11.0.1; until then rewrite the call or stay on .NET 10.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
If an app that worked on .NET 10 starts throwing NullReferenceException on .NET 11.0.0, sometimes on the first call and sometimes only after it has been running for a while, check the top stack frame for a call like enumValue.Equals(nullableEnum). The .NET 11.0.0 JIT folds Enum.Equals into a direct comparison and forgets that a boxed Nullable<TEnum> can be null. The fix (dotnet/runtime#137392) is merged into release/11.0 and is expected in the 11.0.1 servicing release. Until you can run on 11.0.1, rewrite the call as x == y in code you own, and keep library-heavy apps (iText, Testcontainers.Kafka, Open XML SDK) on .NET 10 or run them with DOTNET_JITMinOpts=1.
Everything below was reproduced on .NET SDK 11.0.100 with runtime 11.0.0 (osx-arm64, Apple M4), compared against runtime 10.0.14 on the same machine, and with iText 9.8.0. The original reports are on Windows x64 and Linux x64, so this is not platform-specific.
The error in context
In your own code it looks like this:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Program.<<Main>$>g__AreEqual|0_14(DayOfWeek x, Nullable`1 y)
at Program.<Main>$(String[] args)
More often it surfaces inside a library, which makes it look like a library bug. Here are two traces from iText 9.8.0 on .NET 11.0.0, same program, different runs:
System.NullReferenceException: Object reference not set to an instance of an object.
at iText.Layout.Element.Paragraph.SetFixedLeading(Single leading)
System.NullReferenceException: Object reference not set to an instance of an object.
at iText.Layout.Renderer.CellRenderer.ApplyBorderBox(Rectangle rect, Border[] borders, Boolean reverse)
at iText.Layout.Renderer.AbstractRenderer.ApplyBorderBox(Rectangle rect, Boolean reverse)
at iText.Layout.Renderer.AbstractRenderer.CalculateAdditionalWidth(AbstractRenderer renderer)
at iText.Layout.Renderer.BlockRenderer.GetMinMaxWidth(Nullable`1 parentBoxWidth)
Other traces reported against the same bug include LineRenderer.Layout, CellRenderer.ApplyMargins, TextRenderer.CalculateAscenderDescender, UlOlTagCssApplier.Apply (iText pdfHTML) and Testcontainers.Kafka.KafkaBuilder.Build(). A Stack Overflow question about iText table layout on .NET 11 hit it on iteration 483 of a PDF loop. On Windows the process can also exit with code -1073741819 (0xC0000005).
Why this happens
dotnet/runtime#122779 (“Intrinsify Enum.Equals to avoid boxing”) taught the .NET 11 JIT to replace Enum.Equals(object) with a direct comparison of the two values when both operands are known to be the exact same enum type. That is a good optimization for a.Equals(b) where both are DayOfWeek.
The problem is what C# emits for x.Equals(y) when x is DayOfWeek and y is DayOfWeek?:
ldarga.s x
ldarg.1
box valuetype System.Nullable`1<valuetype System.DayOfWeek>
constrained. System.DayOfWeek
callvirt instance bool System.Object::Equals(object)
Boxing a Nullable<DayOfWeek> produces either a boxed DayOfWeek or null. The JIT correctly concludes that the exact type of the boxed argument is DayOfWeek, but in gtFoldExprCall it threw away the “is this non-null” answer (the variable was literally declared as bool isNonNull; // Unused here.). So the folded code reads the payload of the argument without a null check, and a null argument dereferences address zero instead of returning false. The runtime issue is #133817; the one-line fix in #133826 adds !isArg1NonNull to the bail-out condition.
The fix landed in main on 2026-09-24, after release/11.0 had branched, so 11.0.0 shipped without it (#137270). The backport #137392 was merged into release/11.0 on 2026-11-13 with the Servicing-approved label, and a JIT team member confirmed on #137382 that it should be in 11.0.1.
The fold only happens in optimized code. That is why the failure looks random:
- Tier 0 code (what every method starts as) is not affected, so short runs and unit tests pass.
- After a method is called about 30 times and the tiering delay passes, it is recompiled at tier 1 with full optimizations. From then on, every call with a
nullnullable throws. - A method that calls
Equalsinside a hot loop is switched to optimized code by on-stack replacement (OSR) after roughly 10,000 loop iterations, even if the method itself is called only once. - With
DOTNET_TieredCompilation=0,[MethodImpl(MethodImplOptions.AggressiveOptimization)]or Native AOT, the code is optimized from the start, so the first call throws.
If you want the background on tier 0, tier 1 and OSR, the post on how tiered compilation decides what to optimize covers the mechanics.
Minimal repro
// .NET 11.0.0 (SDK 11.0.100), C# 15, Release build
using System.Runtime.CompilerServices;
Console.WriteLine($"Runtime {Environment.Version}");
var sw = System.Diagnostics.Stopwatch.StartNew();
for (long i = 0; sw.Elapsed.TotalSeconds < 5; i++)
{
try { _ = AreEqual(DayOfWeek.Monday, null); }
catch (NullReferenceException)
{
Console.WriteLine($"NRE at call {i:N0} after {sw.ElapsedMilliseconds} ms");
return;
}
}
Console.WriteLine("no exception in 5 seconds");
[MethodImpl(MethodImplOptions.NoInlining)]
static bool AreEqual(DayOfWeek x, DayOfWeek? y) => x.Equals(y);
Results on this machine:
| Runtime | Settings | Result |
|---|---|---|
| 11.0.0 | default tiering | NRE after about 220 ms (9.5 to 10.3 million calls, 3 runs) |
| 11.0.0 | DOTNET_TieredCompilation=0 | NRE on the first call |
| 11.0.0 | DOTNET_TieredCompilation=0 + DOTNET_JITMinOpts=1 | False, no exception |
| 11.0.0 | Native AOT (osx-arm64, PublishAot=true) | NRE on the first call |
| 10.0.14 | DOTNET_TieredCompilation=0 | False |
| 10.0.14 | default tiering, 5 seconds | no exception |
Note that a fixed 1,000,000-iteration loop finished in well under the tiering delay and never failed. If your repro “works”, run it longer or set DOTNET_TieredCompilation=0.
With iText 9.8.0, a loop that creates a Document containing a two-cell Table (one Paragraph with SetFixedLeading(12)) failed on document 1 with DOTNET_TieredCompilation=0, failed on document 2,040 with default tiering, and completed 20,000 documents both with DOTNET_JITMinOpts=1 on 11.0.0 and with DOTNET_TieredCompilation=0 on 10.0.14.
Fix 1: update to .NET 11.0.1
This is the real fix. As of 2026-12-01 the latest .NET 11 release in the release metadata is still 11.0.0 (released 2026-11-10). .NET servicing releases normally ship on Patch Tuesday, which next falls on 2026-12-08, and the backport is already merged into the 11.0 servicing branch. Once 11.0.1 is out:
- Install the 11.0.1 runtime (or SDK 11.0.101) on every machine and in every base image that runs the app. A framework-dependent app rolls forward to the newest installed patch automatically.
- Rebuild and redeploy anything that carries its own runtime. Self-contained and Native AOT apps embed the 11.0.0 JIT output or runtime, so installing a new shared runtime does not fix them. Native AOT in particular has the buggy code compiled into the binary.
- For containers, pull the new
mcr.microsoft.com/dotnet/runtime:11.0oraspnet:11.0image and rebuild; a cached 11.0.0 layer keeps the bug. - Verify with the probe in the next section instead of trusting the version number in a Dockerfile.
Fix 2: rewrite the comparison in code you own
The bug needs exactly this shape: an enum receiver, a boxed Nullable<TEnum> argument, and the virtual Equals(object). Any other way of comparing avoids it. This matrix ran every variant in a method marked [MethodImpl(MethodImplOptions.AggressiveOptimization)], so each one is compiled with full optimizations on the first call, with x = DayOfWeek.Monday and y = null:
// .NET 11.0.0, C# 15. Each line is the body of an AggressiveOptimization method.
x.Equals(y) // NullReferenceException
x.Equals((object?)y) // NullReferenceException
x.Equals((object?)null) // False (a null literal has no exact type)
Generic<T>(T x, T? y) => x.Equals(y) // NullReferenceException (T : struct, Enum)
x == y // False
y.Equals(x) // False
object.Equals(x, y) // False
Nullable.Equals<DayOfWeek>(x, y) // False
EqualityComparer<DayOfWeek?>.Default.Equals(x, y) // False
y is DayOfWeek v && x == v // False
The Native AOT build gave the identical result for every row, and on .NET 10.0.14 every row returned False. With a non-null y that matches, x.Equals(y) returns True on 11.0.0 as expected; only the null case is broken.
The cleanest replacement is the lifted equality operator:
// .NET 11.0.0, C# 15
// Before: throws on .NET 11.0.0 when status is null and the method is optimized
if (current.Equals(status)) { /* ... */ }
// After: compiles to a HasValue check plus an integer compare, no boxing at all
if (current == status) { /* ... */ }
x == y also avoids boxing entirely, so it is the better code on every runtime, not just a workaround. In generic code constrained to struct, Enum, where == is not available, use EqualityComparer<T?>.Default.Equals(x, y) or Nullable.Equals(x, y).
[MethodImpl(MethodImplOptions.NoOptimization)] on the method also returns False, but it disables optimization for the whole method body. Prefer rewriting the comparison.
Fix 3: when the call is inside a library
You cannot rewrite a call inside iText. The options, in order:
- Stay on
net10.0until 11.0.1 ships. Multi-target if you need to, or simply hold the upgrade a week. This is what the people on the runtime issue did. - Run the process with
DOTNET_JITMinOpts=1. The JIT then never optimizes, so the fold never happens. It must be an environment variable: puttingJITMinOptsorSystem.Runtime.JITMinOptsinruntimeconfig.jsonconfigPropertieshad no effect in this test, and the probe still reported the bug. The cost is real. A tight array-summing loop took 220 ms normally and 423 to 442 ms with MinOpts (3 runs each). The iText loop that generates 20,000 documents took 11.3 to 11.6 seconds with MinOpts on 11.0.0 against 4.08 to 4.11 seconds with default settings on 10.0.14. Treat it as an emergency switch, not a deployment setting. - Ask the library for a patch. Changing
a.Equals(b)toa == bis a trivial change, and some maintainers will ship it. Your fix still disappears with 11.0.1 either way.
DOTNET_TC_CallCounting=0 looks tempting because it keeps methods at tier 0. It is not a fix: it stopped the per-call failure, but a loop that called x.Equals(y) in its body still threw at iteration 9,999 because OSR compiles the loop with full optimizations regardless.
Detect the bug at startup
A runtime version check is fragile (self-contained apps, custom builds, future regressions). Asking the JIT directly is more reliable. A method marked AggressiveOptimization skips tier 0, so it reproduces the bug on the first call:
// .NET 11, C# 15
using System.Runtime.CompilerServices;
public static class EnumEqualsJitBug
{
// Compiled straight to fully optimized code, like hot tier-1 code.
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
private static bool Probe(DayOfWeek x, DayOfWeek? y) => x.Equals(y);
public static bool IsPresent()
{
try { return Probe(DayOfWeek.Monday, null); }
catch (NullReferenceException) { return true; }
}
}
On 11.0.0 this prints True under the JIT and under Native AOT, and False with DOTNET_JITMinOpts=1 set. Wire it into a health check or log it at startup so you know when a host is still on an unpatched runtime.
Find affected call sites in your dependencies
To know whether a given package is exposed, scan its IL for the exact pattern: box Nullable<TEnum>, then constrained., then callvirt Equals(object). This small console app loads every .dll in a folder (point it at your bin output) and prints the matching methods:
// .NET 11, C# 15. Usage: dotnet run -- <folder with the app's .dll files>
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Loader;
var dir = Path.GetFullPath(args[0]);
var alc = new AssemblyLoadContext("scan");
alc.Resolving += (ctx, name) =>
{
var p = Path.Combine(dir, name.Name + ".dll");
return File.Exists(p) ? ctx.LoadFromAssemblyPath(p) : null;
};
var oneByte = new OpCode[0x100];
var twoByte = new OpCode[0x100];
foreach (var f in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static))
{
var op = (OpCode)f.GetValue(null)!;
if (op.Size == 1) oneByte[op.Value & 0xFF] = op; else twoByte[op.Value & 0xFF] = op;
}
int hits = 0;
foreach (var file in Directory.GetFiles(dir, "*.dll"))
{
Assembly asm;
try { asm = alc.LoadFromAssemblyPath(file); } catch { continue; }
Type?[] types;
try { types = asm.GetTypes(); } catch (ReflectionTypeLoadException e) { types = e.Types; }
foreach (var type in types)
{
if (type is null) continue;
const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
foreach (MethodBase m in type.GetMethods(all).Cast<MethodBase>().Concat(type.GetConstructors(all)))
{
byte[]? il;
try { il = m.GetMethodBody()?.GetILAsByteArray(); } catch { continue; }
if (il is null) continue;
var ops = Decode(il);
for (int i = 0; i + 2 < ops.Count; i++)
{
if (ops[i].Op != OpCodes.Box || ops[i + 1].Op != OpCodes.Constrained ||
ops[i + 2].Op != OpCodes.Callvirt) continue;
try
{
var boxed = m.Module.ResolveType(ops[i].Token, Generic(m.DeclaringType), Generic(m));
if (!boxed.IsGenericType || boxed.GetGenericTypeDefinition() != typeof(Nullable<>)) continue;
var arg = boxed.GetGenericArguments()[0];
if (!arg.IsEnum && !arg.IsGenericParameter) continue;
var callee = m.Module.ResolveMethod(ops[i + 2].Token, Generic(m.DeclaringType), Generic(m));
if (callee?.Name != "Equals" || callee.GetParameters().Length != 1) continue;
hits++;
Console.WriteLine($"{Path.GetFileName(file)}: {type.FullName}.{m.Name} (Nullable<{arg.Name}>)");
}
catch { }
}
}
}
}
Console.WriteLine($"{hits} call site(s)");
static Type[]? Generic(MemberInfo? m) => m switch
{
Type t when t.IsGenericType => t.GetGenericArguments(),
MethodInfo mi when mi.IsGenericMethod => mi.GetGenericArguments(),
_ => null
};
List<(OpCode Op, int Token)> Decode(byte[] il)
{
var list = new List<(OpCode, int)>();
for (int pos = 0; pos < il.Length;)
{
OpCode op = il[pos] == 0xFE ? twoByte[il[++pos]] : oneByte[il[pos]];
pos++;
int token = 0;
switch (op.OperandType)
{
case OperandType.InlineNone: break;
case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI:
case OperandType.ShortInlineVar: pos += 1; break;
case OperandType.InlineVar: pos += 2; break;
case OperandType.InlineI8: case OperandType.InlineR: pos += 8; break;
case OperandType.InlineSwitch: pos += 4 + BitConverter.ToInt32(il, pos) * 4; break;
default: token = BitConverter.ToInt32(il, pos); pos += 4; break;
}
list.Add((op, token));
}
return list;
}
Pointed at the build output of the iText repro, it reported 27 call sites: 26 in itext.layout.dll and 1 in itext.forms.dll. The list includes Paragraph.SetFixedLeading, CellRenderer.ApplyBorderBox and LineRenderer.Layout (all comparing a Nullable<RenderingMode> or Nullable<BorderCollapsePropertyValue>), which are exactly the frames in the stack traces above. Run against the repro app itself, it found every throwing variant from the matrix and none of the safe ones.
The scanner is a heuristic. It catches what the C# compiler emits for enumValue.Equals(nullableEnum). It does not catch the rarer shape where both values are first stored in object locals and then compared (object a = x; object b = y; a.Equals(b)), which the original issue also shows failing. Treat zero hits as “probably safe”, not as proof.
Gotchas and lookalikes
- “It only fails in production.” Production processes run long enough for tier-up and OSR; unit tests usually do not. Run your tests with
DOTNET_TieredCompilation=0once after upgrading to any new major runtime. It makes optimizer bugs deterministic. - Debug builds are not immune. Tiering is a runtime decision. A Debug build of your code disables optimization for your assemblies, but a Release-built NuGet dependency like iText still tiers up.
- ReadyToRun did not trip it here. A
PublishReadyToRun=truebuild of the repro returnedFalseon the first call, probably becauseDayOfWeeklives in CoreLib outside the app’s version bubble. Hot R2R methods are still rejitted at tier 1 later, so R2R is not a workaround. - Not every NRE after an upgrade is this bug. If the frame does not involve an enum and a nullable enum, look at ordinary causes first. The .NET 8 to .NET 11 migration checklist lists the documented breaking changes.
- Native AOT apps fail on the first call because all code is optimized ahead of time. If you ship Native AOT, the trade-offs in Native AOT vs ReadyToRun vs JIT in .NET 11 apply: you must rebuild to pick up the 11.0.1 fix.
Related
- What is tiered compilation and how do I reason about it explains why the failure appears only after warm-up.
- What Native AOT is and what it costs you covers why AOT binaries need a rebuild for runtime fixes.
- Native AOT vs ReadyToRun vs JIT in .NET 11 compares the three code generation modes this bug behaves differently in.
- Rider 2026.1’s ASM viewer is a convenient way to look at the generated code for a suspicious method yourself.
- Migrate from .NET 8 to .NET 11: the full checklist for the rest of the upgrade.
Sources
- dotnet/runtime#133817: Enum.Equals folding throws NullReferenceException instead of returning false for a null argument
- dotnet/runtime#133826: Fix Enum.Equals folding for nullable boxed arguments
- dotnet/runtime#137392: the release/11.0 backport
- dotnet/runtime#137270: fix not in release/11.0 (Testcontainers.Kafka, iText, Open XML SDK reports)
- dotnet/runtime#137382: iText NullReferenceException on .NET 11.0.0
- dotnet/runtime#122779: Intrinsify Enum.Equals to avoid boxing
- Stack Overflow: Intermittent NullReferenceException in iText 9.8.0 table layout on .NET 11
- .NET 11 release metadata
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.