In C#, why does `int count = profile?.Tags.Count;` fail to compile, and what type does `?.` give a value-type member?
answer
- null must fit the result
- int becomes Nullable<int>
- error CS0266
- ?? 0 or GetValueOrDefault
basics
~20 sThe ?. operator must be able to return null, so a non-nullable value-type member such as Count (an int) comes back as int?. Assigning an int? to an int is error CS0266; add ?? 0 to get an int.
solid answer
~40 sWhen the member reached through `?.` or `?[]` is a non-nullable value type `T`, the expression's type is `T?`, i.e. `Nullable<T>`, because null is the result when the receiver is null. So `profile?.Tags.Count` is `int?`, and assigning it to `int` fails with CS0266. Fix it with `profile?.Tags.Count ?? 0` or `GetValueOrDefault()`. Comparisons on the result are lifted: `profile?.Tags.Count > 0` is `false` for a null profile. The same rule makes `nextId?.Invoke()` on a `Func<int>` an `int?`, while `Action` invocations stay `void`. In a generic method with unconstrained `T`, `box?.Value` is error CS8978 because the compiler cannot pick between `Nullable<T>` and a null reference.
code
csharp · 16 linesProfile? profile = LoadProfile(signedIn: false);
var tagCount = profile?.Tags.Count; // int?, because Count is an int
int shown = profile?.Tags.Count ?? 0; // ?? turns it back into an int
Func<int>? nextAvatarId = null;
var avatarId = nextAvatarId?.Invoke(); // int?, from a Func<int>
Console.WriteLine(tagCount.HasValue); // False
Console.WriteLine(shown); // 0
Console.WriteLine(avatarId.HasValue); // False
Console.WriteLine(profile?.Tags.Count > 0); // False: the comparison with null is false
static Profile? LoadProfile(bool signedIn) => signedIn ? new Profile(["admin"]) : null;
record Profile(List<string> Tags);go deeper
Recall that ?. on an int property gives an int?, and that ?? 0 gets back a plain int.
Explain why null must fit the result, name CS0266 and CS8978, and show how ?.Invoke follows the same rule.
Catch conditions that silently treat a null receiver as false through lifted comparisons, and prefer an explicit fallback in review.
Decide where nullable results stop in a codebase: convert to a plain value at the boundary rather than spreading int? through the logic.
## The rule: a value-type result becomes nullable `?.` and `?[]` must be able to produce null. When the accessed member is a **reference type** (`string`, `Address`), null is already a possible value, so the type stays the same. When it is a **non-nullable value type** `T` (`int`, `bool`, `DateTime`, a struct), it cannot hold null, so the C# documentation states that `a?.x` is of the corresponding **nullable value type** `T?`, that is `Nullable<T>`. | Accessed member | Type of `a.x` | Type of `a?.x` | |---|---|---| | `List<string>.Count` | `int` | `int?` | | `string.Length` | `int` | `int?` | | `Profile.Address` (class) | `Address` | `Address` (null possible) | | `Func<int>.Invoke()` | `int` | `int?` | | `Action<string>.Invoke(...)` | `void` | `void` (statement only) | Hence `int count = profile?.Tags.Count;` fails with **error CS0266**: "Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)". The compiler is right: when `profile` is null there is no `int` to give you. ## Getting a plain value back 1. `profile?.Tags.Count ?? 0` — the usual fix; `??` with an `int` right operand yields `int`. 2. `(profile?.Tags.Count).GetValueOrDefault()` — the same result through the `Nullable<T>` API. 3. A cast `(int)(profile?.Tags.Count)` compiles but throws `InvalidOperationException` when the value is null, which reintroduces the crash you were avoiding. Note that the type is decided by the **last** member in the chain: in `profile?.Tags.Count` the `?.` sits after `profile`, yet `Count` is what makes the result `int?`. Inside the chain nothing is lifted. In `profile?.Tags.Count.ToString()`, `Count` is a plain `int` whenever it is reached, so `ToString()` is `int.ToString()` and the whole expression is a possibly-null `string`: null when `profile` is null. Parenthesize instead, `(profile?.Tags.Count).ToString()`, and the call is `Nullable<int>.ToString()` on the finished `int?`, which returns an empty string for null rather than null. Two spellings, two different results for a missing profile. ## Comparisons on the nullable result Because the result is `int?`, comparisons use the lifted operators of nullable value types. The documentation's own example: `numbers?.Length < 2` evaluates to `false` when `numbers` is null, and `profile?.Tags.Count > 0` is `false` too. A condition such as `if (!(profile?.Tags.Count > 0))` therefore reads "no tags" for a missing profile, which may or may not be what you meant. Write `(profile?.Tags.Count ?? 0) > 0` to make the decision explicit. The full rules for lifted comparisons belong to the lesson on nullable value types. ## `?.Invoke` on delegates A delegate variable that may be unset is invoked with `callback?.Invoke(args)`. The shorter `callback?(args)` is not valid C#: the parser reads `?(` as the start of a conditional operator and reports error CS1003 (`':' expected`). The rules above apply unchanged: - `Action<string>? onSaved` gives `onSaved?.Invoke("x")`, a statement with no value; `var v = onSaved?.Invoke("x");` fails with CS0815 because the result is `void`. - `Func<int>? nextAvatarId` gives `nextAvatarId?.Invoke()`, an `int?`. - The delegate is read once, so a handler removed by another thread between the test and the call cannot cause a `NullReferenceException`; how events use this is covered with events. ## Unconstrained generics: error CS8978 Inside a generic method the compiler must choose between "wrap in `Nullable<T>`" and "a null reference". With an unconstrained `T` it cannot, so `box?.Value` where `Value` is of type `T` is **error CS8978**: "'T' cannot be made nullable." The fixes are a constraint: - `where T : struct` — the result is `Nullable<T>`; - `where T : class` — the result is a possibly-null `T`. An unconstrained `T?` return type does not help, because there `T?` is only an annotation meaning "may be default", not `Nullable<T>`; that distinction is covered with the flow-analysis attributes. ## Summary for an interview - `?.` on a value-type member yields `T?`; assigning it to `T` is CS0266. - `?? fallback` or `GetValueOrDefault()` gets back a `T` without throwing. - Comparisons on the result are lifted and are false for null. - `?.Invoke()` is how to call a possibly-null delegate; `Func<int>` gives `int?`. - Unconstrained `T` with `?.` is CS8978; add `struct` or `class`.
- Why is `callback?(args)` rejected while `callback?.Invoke(args)` compiles?In an expression, `?(` is not a null-conditional form: only `?.` and `?[` are. The parser reads `callback?(args)` as the start of a conditional `c ? a : b`, so the compiler reports CS1003, `':' expected`. Calling `Invoke` explicitly turns the call into a member access that `?.` can guard.
- Is `(int)(profile?.Tags.Count)` a safe way to get an int?No. The explicit conversion from `int?` to `int` reads `Nullable<int>.Value`, which throws `InvalidOperationException` when the value is null. It compiles, but it moves the failure to run time. Use `?? 0` or `GetValueOrDefault()` when a missing profile should count as zero.
- profile?.Tags.Count is an int because Count can never be null
- ?. returns 0 for an int member when the receiver is null
- A cast to int is a safe fix for the CS0266 error
- callback?(args) is the short form of callback?.Invoke(args)
- An unconstrained T works with ?. because T? means Nullable<T>