In C#, why does reading Length on an ImmutableArray<decimal> property that was never assigned throw NullReferenceException, and how do you guard against it?
answer
- it is a struct, not a class
- default wraps a null array
- IsDefault versus IsEmpty
- initialise to Empty or []
basics
~20 sImmutableArray<T> is a struct wrapping an array, and its default value wraps null. Length, the indexer, Add and foreach use that null array and throw NullReferenceException. Initialise to ImmutableArray<T>.Empty or [], and test IsDefault at boundaries.
solid answer
~40 s`ImmutableArray<T>` is a `readonly struct` whose only field is a `T[]`. A struct can never be null, so an unassigned field or property, a `default` literal, or an element of `new ImmutableArray<T>[n]` is `default(ImmutableArray<T>)`, which wraps a **null array**. The struct's own members (`Length`, the indexer, `Add`, `foreach`) dereference that array and throw `NullReferenceException`; the source keeps `Length` and the indexer branch-free on purpose so the JIT can drop bounds checks. Through an interface (`IReadOnlyList<T>.Count`, LINQ over a boxed value) the same instance throws `InvalidOperationException` saying the operation cannot be performed on a default instance. Guard by initialising to `ImmutableArray<T>.Empty` or `[]`, checking `IsDefault` or `IsDefaultOrEmpty` where values enter, and remembering that a default array is not equal to an empty one.
code
csharp · 23 linesusing System.Collections.Immutable;
var cache = new RateCache(); // Rates never assigned
Console.WriteLine(cache.Rates.IsDefault); // True
Try(() => cache.Rates.Length); // NullReferenceException
Try(() => cache.Rates.Add(1.10m).Length); // NullReferenceException
Try(() => ((IReadOnlyList<decimal>)cache.Rates).Count); // InvalidOperationException
Console.WriteLine(cache.Rates.IsDefaultOrEmpty); // True
ImmutableArray<decimal> empty = [];
Console.WriteLine(empty.IsDefault); // False: a real, empty array
static void Try(Func<object> read)
{
try { Console.WriteLine(read()); }
catch (Exception ex) { Console.WriteLine(ex.GetType().Name); }
}
class RateCache
{
public ImmutableArray<decimal> Rates { get; set; } // default(ImmutableArray<decimal>)
}go deeper
Recall that ImmutableArray<T> is a struct and should always be initialised, for example to ImmutableArray<T>.Empty.
Explain that the default value wraps a null array and that IsDefault and IsDefaultOrEmpty exist to detect it.
Diagnose the two exception types from one bug, list where default values come from, and guard boundaries with IsDefault checks.
Weigh the struct's allocation-free reads against the default-value hazard when choosing it for public API surfaces.
## The symptom A rates cache exposes `public ImmutableArray<decimal> Rates { get; set; }`. A code path forgets to assign it, and the first `cache.Rates.Length` throws `NullReferenceException`. Nobody wrote `null` anywhere, nullable reference type analysis said nothing, and the type is called *immutable*, which sounds safe. ## Why a struct can hold a null `ImmutableArray<T>` is a **`readonly struct`** with a single field: `internal readonly T[]? array`. It is a struct so that holding one costs no extra allocation; it is the array, with an immutable face. Every struct type has a **default value** in which all its fields are zeroed. For `ImmutableArray<T>`, that means the array field is `null`. You get the default value whenever nothing assigns a real one: - an unassigned field or auto-property of type `ImmutableArray<T>` in a class; - `default` or `default(ImmutableArray<T>)` written explicitly; - the elements of a freshly created `ImmutableArray<T>[]`; - an `out` parameter on a miss, such as `Dictionary<string, ImmutableArray<int>>.TryGetValue` returning `false`; - `ImmutableCollectionsMarshal.AsImmutableArray(null)`, which the source documents as returning an uninitialised value. The variable is not null (a struct cannot be), and nullable warnings do not apply. `cache.Rates is null` does not even compile: the SDK reports CS0037, "Cannot convert null to 'ImmutableArray<decimal>' because it is a non-nullable value type". Confusingly, `cache.Rates == null` does compile, through the type's `==` overload for `ImmutableArray<T>?`, and returns `true` for a default instance. `IsDefault` says what you mean. ## What throws, and which exception The struct exposes `IsDefault` (`array == null`) and `IsDefaultOrEmpty`, and two families of members behave differently on a default instance: | Access | On a default `ImmutableArray<T>` | |---|---| | `Length`, `this[int]`, `IsEmpty` | `NullReferenceException` | | `Add`, `CopyTo`, `foreach` over the struct | `NullReferenceException` | | `IReadOnlyList<T>.Count`, `IList<T>` indexer, `IEnumerable<T>.GetEnumerator()` | `InvalidOperationException` | | `IsDefault`, `IsDefaultOrEmpty` | safe: `true` | The split is deliberate. The source comments explain that `Length` and the indexer must stay trivially simple so that the JIT can remove array bounds checks in loops, so they do not test for null and simply let the hardware fault. Explicitly implemented interface members, which are slower anyway, check first and throw `InvalidOperationException` with the message "This operation cannot be performed on a default instance of ImmutableArray<T>. Consider initializing the array, or checking the ImmutableArray<T>.IsDefault property." So the same bug shows up as a different exception depending on whether the code used the struct directly or through an interface after boxing. ## How to guard against it 1. **Initialise every field and property.** Write `= ImmutableArray<decimal>.Empty;` or, since C# 12, `= [];`. Both give a real, zero-length array, for which `IsDefault` is `false`. 2. **Check at the boundaries.** Where an `ImmutableArray<T>` arrives from outside (a constructor argument, a deserialised object, a dictionary miss), test `IsDefault` and either throw a clear `ArgumentException` or substitute `Empty`. 3. **Use `IsDefaultOrEmpty`** when "nothing assigned" and "assigned but empty" mean the same thing to the caller. 4. **Do not compare with `Empty` to detect the default.** `ImmutableArray<T>` equality compares the underlying array references, so `default(ImmutableArray<T>) == ImmutableArray<T>.Empty` is `false`. A constructor guard at a boundary looks like this: ```csharp public RateCache(ImmutableArray<decimal> rates) { if (rates.IsDefault) throw new ArgumentException("Rates must be initialised.", nameof(rates)); Rates = rates; } ``` Substituting instead of throwing is equally valid when "no rates" is a legitimate input: `Rates = rates.IsDefault ? ImmutableArray<decimal>.Empty : rates;`. `ImmutableArray<T>.Empty` is a single shared static instance per element type, so using it costs no allocation. ## Spotting it in a debugger The type carries a debugger display that shows `Uninitialized` for a default instance and `Length = n` otherwise. When a watch window shows `Uninitialized` on a field that should hold data, the bug is a missing assignment, not a cleared array. That is quicker to read than the exception, which points at whichever member happened to be touched first. ## Related costs of being a struct - Passing an `ImmutableArray<T>` as `IEnumerable<T>` or `IReadOnlyList<T>` **boxes** it, allocating a small object. Code that cares about allocations keeps it as the struct type. - Updating a shared `ImmutableArray<T>` field from several threads uses the `ImmutableInterlocked` overloads that take `ref ImmutableArray<T>`, such as `Update` and `InterlockedCompareExchange`, which swap the wrapped array atomically. None of this applies to `ImmutableList<T>`, which is a class: an unassigned `ImmutableList<T>` is an ordinary null reference, and nullable analysis warns about it like any other.
- Why does nullable reference type analysis not warn about a default ImmutableArray<T>?Nullable analysis tracks references that may be null. `ImmutableArray<T>` is a struct, so the variable itself can never be null and there is nothing for the analysis to flag; the null lives in a private field. Only `IsDefault` reveals it.
- Why do the struct's members throw NullReferenceException instead of a clearer exception?Performance. The source keeps `Length` and the indexer free of any null check so the JIT can recognise them as array accesses and eliminate bounds checks in loops. A default instance therefore faults on the null array, while the slower interface members afford an explicit check.
- Is ImmutableArray<T>.Empty the same as default(ImmutableArray<T>)?No. `Empty` wraps a real zero-length array, so `Length` is 0 and every member works; `default` wraps null and most members throw. Equality compares the underlying arrays, so the two are not equal either.
- An ImmutableArray<T> property can be checked with is null
- default(ImmutableArray<T>) is just an empty array
- Nullable reference types will warn about an unassigned ImmutableArray<T>
- IsEmpty is the safe way to test a possibly default ImmutableArray<T>
- Comparing with ImmutableArray<T>.Empty is how to detect a default instance