In C#, why does a constructor that calls an Initialize helper to set non-nullable fields still get CS8618, and how does [MemberNotNull] fix it?
answer
- each constructor checked on its own
- calls are not followed
- promise members by name
- a bool-returning variant exists
basics
~20 sThe compiler checks each constructor without following calls, so fields set only in Initialize look unassigned and CS8618 fires. [MemberNotNull(nameof(_prices), nameof(_region))] on Initialize promises they are not-null on return, and the compiler checks the helper.
solid answer
~40 sWith nullable enabled, every non-nullable field and auto-property must hold a non-null value when each constructor exits. The analysis works one method at a time, so `public PriceCache(string region) => Initialize(region);` looks as if it leaves `_prices` and `_region` null, and the constructor gets CS8618. Putting `[MemberNotNull(nameof(_prices), nameof(_region))]` on the helper tells the analysis those members are not-null after any call to it, which also lets a `Reset()` method reuse it. The compiler verifies the helper: forgetting a named member reports CS8774, and naming something that is not a field or property gives CS8776. For a `bool` helper or property, `[MemberNotNullWhen(true, ...)]` ties the promise to the result. Constructor chaining, field initializers and `required` are the alternatives.
code
csharp · 28 linesusing System.Diagnostics.CodeAnalysis;
var cache = new PriceCache("eu");
cache.Add("sku-1", 9.99m);
Console.WriteLine(cache.Describe());
cache.Reset();
Console.WriteLine(cache.Describe());
class PriceCache
{
private Dictionary<string, decimal> _prices;
private string _region;
public PriceCache(string region) => Initialize(region); // no CS8618
public void Reset() => Initialize(_region);
public void Add(string sku, decimal price) => _prices[sku] = price;
public string Describe() => $"{_region}: {_prices.Count} prices";
[MemberNotNull(nameof(_prices), nameof(_region))]
private void Initialize(string region)
{
_prices = new Dictionary<string, decimal>();
_region = region;
}
}go deeper
Recall that CS8618 means a non-nullable field may still be null when a constructor finishes, and that the warning is checked per constructor.
Explain why a helper call hides the assignments, and how [MemberNotNull] with nameof restores the analysis without changing run-time behaviour.
Show how the compiler verifies the helper with CS8774 and CS8776, when [MemberNotNullWhen] fits, and why = null! weakens future constructors.
Set a team rule for initialisation helpers versus constructor chaining and required members, so suppressions such as = null! need justification.
## The rule behind CS8618 With **nullable reference types** enabled, a field declared `string _region` promises it is never null. The compiler enforces that promise where objects are created: at the end of **every constructor**, each non-nullable reference field and auto-property must be *not-null*. Otherwise it reports **CS8618**: "Non-nullable field '_region' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the field as nullable." It is a warning, not an error, unless the project turns nullable warnings into errors. ## Why a helper call is invisible The in-memory cache in this example builds its state in one place so that a `Reset()` method can rebuild it later: ```csharp public PriceCache(string region) => Initialize(region); public void Reset() => Initialize(_region); private void Initialize(string region) { _prices = new Dictionary<string, decimal>(); _region = region; } ``` The constructor still gets CS8618 for both fields. Nullable analysis treats each method separately; at the call `Initialize(region)` it reads the helper's **signature**, which says nothing about fields. As far as the constructor's analysis knows, `_prices` and `_region` are still at their default value, null. ## [MemberNotNull] `MemberNotNullAttribute`, in `System.Diagnostics.CodeAnalysis`, is a **postcondition about members of the same type**: ```csharp [MemberNotNull(nameof(_prices), nameof(_region))] private void Initialize(string region) { ... } ``` After any call to `Initialize`, the analysis marks the listed members not-null. The constructor's warning disappears, and `Reset()` keeps reusing the same helper. Details worth knowing: - It goes on a **method or property**, never on the field: on a field the compiler reports error CS0592. - It has a `params string[]` constructor, and the attribute may be applied more than once, so you can list several members. - Use `nameof(...)` rather than string literals, so renaming a field cannot silently break the promise. - It can name **auto-properties** as well as fields, which helps when a non-nullable `string Name { get; private set; }` is set by the helper. - The attribute is metadata only: the helper's IL and the constructor's IL are the same with or without it. ## What the compiler verifies The promise is checked inside the helper, so it cannot drift: 1. If the helper can return while a listed member may still be null, it reports **CS8774** ("Member '_tag' must have a non-null value when exiting."). The constructor that calls it does not get CS8618 for that member, because the attribute is trusted at the call; the warning lands in the helper instead. 2. Naming something that is not a field or property of the type, such as a method or a misspelled name, reports **CS8776** ("Member 'Missing' cannot be used in this attribute."). ## [MemberNotNullWhen] for bool results Some members initialise state only on success. `[MemberNotNullWhen(true, nameof(_body))]` on a `bool` method or property says: when this returns `true`, `_body` is not-null. ```csharp private string? _body; [MemberNotNullWhen(true, nameof(_body))] public bool IsLoaded => _body is not null; public int Length() => IsLoaded ? _body.Length : 0; // no warning ``` The getter is checked as well: an `IsLoaded => true` with `_body` possibly null reports **CS8775** ("Member '_body' must have a non-null value when exiting with 'true'."). ## Alternatives and when to prefer them | Approach | When it fits | |---|---| | Field initializers | The value does not depend on constructor arguments | | Constructor chaining with `: this(...)` | Several constructors, one of which does all the work | | `required` members | Callers must supply the value in an object initializer | | `[MemberNotNull]` on a helper | The same initialisation is reused after construction, as `Reset()` does here | | `= null!` on the field | Rarely: it silences CS8618 for every constructor, including one written later that forgets the helper | A practical order of preference is initializers, then chaining, then `required`, with `[MemberNotNull]` kept for helpers that genuinely run more than once. Whatever the choice, the goal is the same: the compiler should be able to prove, for every constructor, that no non-nullable member is left null. The nullable context itself, CS8618 in general and what `required` means are covered with nullable reference types and with fields and properties; `[MemberNotNull]` is the tool for the specific case where initialisation lives in a helper.
- Why not silence CS8618 with = null! on the fields?`= null!` removes CS8618 for every constructor at once, including one added next year that forgets to call `Initialize`; that object then has a null field and nobody is warned. `[MemberNotNull]` keeps the check alive: each constructor must still call a helper whose body the compiler has verified with CS8774.
- What does [MemberNotNullWhen(true, nameof(_body))] on an IsLoaded property buy?It turns the property into a null test the compiler understands: inside `if (IsLoaded)`, `_body` is not-null and `_body.Length` compiles cleanly, while outside it `_body` stays maybe-null. The getter must keep the promise; returning `true` while `_body` may be null reports CS8775.
- The compiler follows calls into private helpers when it analyses a constructor.
- [MemberNotNull] assigns values to the named fields when the program runs.
- Writing = null! on the fields is the same as [MemberNotNull], only shorter.
- [MemberNotNull] goes on the field that the helper sets.
- CS8618 is a compile error, so the class cannot build until it is fixed.