# Nullable values — C#'s null idioms

> A nullable value is spelled and handled as in C#. `x.P is string s` tests a `string?` for null and binds it; `n.GetValueOrDefault()` / `GetValueOrDefault(v)` unwrap an `int?` to its zero or to `v`; `xs?[i]` reads an element of a list that may be null; `p?.X = v;` writes only when `p` is present (C# 14); `Nullable<int>` is `int?`; and `s!.Length` reads off a value promised present. Every one answers what C# answers.

<!-- id: types-nullable · area: types · stability: stable · html: https://osysharp.com/reference/types/nullable/ -->

## Summary        {#summary}
Osy# holds a nullable value as the value itself — there is no `Nullable<T>` wrapper at run time — and every C# idiom
for one means what it means in C#. A `string?`, an `int?`, a `Pt?` and an `int[]?` can be tested, unwrapped, indexed
and written through with the spellings a C# author already has, on every surface: a function, a class method, a
page's `action`, an `[On]` handler, a workflow body and a test.

## Signature      {#signature}
```osy syntax
if (b.S is string s) { … }      // a null test on a `string?`; `s` is the value, present
n.GetValueOrDefault()           // `n ?? 0` — the type's zero when `n` is null
n.GetValueOrDefault(5)          // `n ?? 5`
xs?[0]                          // null when `xs` is null, else the element; the rest of the chain is skipped too
p?.X = 5;                       // writes only when `p` is present; `5` is not evaluated otherwise
xs?[0] = 5;                     // the same for an element
Nullable<int> n = 5;            // `int? n = 5;`
(int?)null                      // a null OF that type — where nothing else gives the null one
int len = s!.Length;            // `s` promised present: the length is an `int`
```

## Description    {#description}

### A null test that binds   {#is-type}
`x is string s` over a value that is **already** a `string?` is C#'s commonest null test: it is true when the value is
present, and `s` is that value with the `?` gone. The same holds for `n is int k` over an `int?`, and for a member —
`b.S is string s` — exactly as in C#. Over a value that cannot be null (`int`, `string`) the test is simply true.

```osy title="a member tested and bound" test app=types-nullable
class Box { public string? Label; }

string Shown(string? label) {
  var box = new Box { Label = label };
  if (box.Label is string text) { return text.ToUpper(); }   // `text` is a `string`, not a `string?`
  return "(none)";
}
```

### `GetValueOrDefault`   {#get-value-or-default}
`Nullable<T>`'s own method. `n.GetValueOrDefault()` answers the value, or the type's zero when there is none — `0`,
`0m`, `false`, `DateTime.MinValue`, `Guid.Empty`; `n.GetValueOrDefault(v)` answers `v` instead. It is `n ?? default`
and `n ?? v`, and compiles to exactly that.

```osy title="the zero, or a value of your own" test app=types-nullable
int Total(int? a, int? b) {
  return a.GetValueOrDefault() + b.GetValueOrDefault(10);     // Total(null, null) is 10; Total(2, 3) is 5
}
```

### `?[]` — an element of a list that may be null   {#null-conditional-index}
`xs?[i]` is `null` when `xs` is, and `xs[i]` otherwise, so its type is the element's, nullable. Like `?.` it skips the
rest of the chain: `rows?[0].Name` reads no `.Name` off a missing list. Pair it with `??` to say what absence means.

```osy title="an element, or a fallback" test app=types-nullable
int FirstOr(int[]? xs, int fallback) {
  return xs?[0] ?? fallback;
}
```

`c ? [1] : [2]` is still a conditional over two collection literals: a `?` written against its operand (`xs?[`) is
the element access, and a spaced `? [ … ] :` is a conditional.

### `?.` on the left of `=`   {#null-conditional-assignment}
C# 14's null-conditional assignment: `p?.X = v;` writes `X` when `p` is present and does nothing when it is null — the
right side is not even evaluated then. Compound forms (`p?.X += 1;`) and an element (`xs?[i] = v;`) work the same
way. A receiver that is a call is evaluated once.

```osy title="written only when present" test app=types-nullable
class Pt { public int X; }

Pt? Same(Pt? p) { return p; }

int Moved() {
  Pt? here = new Pt();
  Pt? nowhere = null;
  here?.X = 5;
  nowhere?.X = 6;          // nothing to write: no fault
  Same(here)?.X += 2;      // `Same` runs once
  return here.X;           // 7
}
```

### `Nullable<T>` spelled out   {#nullable-of-t}
`Nullable<int>` (or `System.Nullable<int>`) is `int?` — the same type, written the long way. `.Value`, `.HasValue` and
`GetValueOrDefault` work on it as on any `int?`.

```osy title="the long spelling" test app=types-nullable
int Spelled() {
  Nullable<int> five = 5;
  Nullable<int> none = null;
  return five.Value + (none.HasValue ? 100 : 0) + none.GetValueOrDefault();   // 5
}
```

### A typed null   {#typed-null}
`(int?)null`, `(string?)null` and `(int[]?)null` are a null **of that type**, as in C#. A bare `null` already takes
the type of whatever it is assigned to, so the cast is rarely needed (the compiler says so, as a warning) — except
where nothing else gives the null a type, such as the receiver of a call: `((int?)null).GetValueOrDefault()` is `0`.

### `!` reads through to the value   {#null-forgiving}
`s!` promises a `string?` present (see [x! — the null-forgiving operator](https://osysharp.com/reference/types/null-forgiving/)), and what is read off it is then present too:
`int len = s!.Length;` is an `int`, as in C#, in every body — a function, an `action`, an `[On]` handler, a workflow
body, a test.

```osy title="a length read off a promised string" test app=types-nullable
int LengthOf(string? s) {
  int len = s!.Length;
  return len;
}
```

## Examples       {#examples}
```osy title="the idioms together" test app=types-nullable
string Summary(Box? box, int[]? counts) {
  box?.Label = "seen";
  int first = counts?[0] ?? 0;
  Nullable<int> extra = null;
  string label = "none";
  var seen = box?.Label;
  if (seen is string l) { label = l; }
  return $"{label}:{first + extra.GetValueOrDefault()}";
}
```

## See also       {#see-also}
- [Optional and required members](https://osysharp.com/reference/types/optional-and-required/) — how a type is spelled nullable in the first place
- [x! — the null-forgiving operator](https://osysharp.com/reference/types/null-forgiving/) — `x!`, the compile-time promise that a value is present
- [Sum / Average / Min / Max / Count](https://osysharp.com/reference/query/aggregates/) — `Max`/`Min`/`Average` answer null over no rows; `??` and `GetValueOrDefault` say what that means
