# The null that is not there

> How Option<T> represents missing values and compares with C# nullable reference types, how to use it without drowning in match, converting to Result, and its runtime cost.

- Author: Zeeshan Adil (https://www.internalswithzee.com/about)
- Published: 2026-09-06
- Updated: 2026-11-21
- Source: https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-option-vs-csharp-null

Chapter 10 of 16 of [Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers.md). Part II, Working knowledge.

This chapter builds on enums and `Result`. Your goal is to distinguish an absent value from a failed operation, then choose an explicit default or error. Start with the lookup examples; the layout discussion is optional for everyday use.

`Option` is the other enum you will use constantly, and it is built from the same parts:

```rust
enum Option<T> {
    Some(T),
    None,
}
```

Rust references cannot be null. Optional values normally use `Option`, which requires you to handle absence before accessing the payload. Raw pointers can still be null, even when created in safe code; dereferencing them requires an unsafe operation.

```rust
fn find_server(id: u32) -> Option<Server> { /* ... */ }

match find_server(7) {
    Some(server) => println!("{}", server.hostname),
    None => println!("not found"),
}
```

## The honest comparison with nullable reference types

C# 8 added nullable reference types, and it is a genuine improvement. It is also a different kind of thing, and the difference is worth being precise about because the marketing blurs it.

Nullable annotations are static analysis over a runtime that still has `null`. Microsoft's [own documentation](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references) says it directly: the annotation does not change the runtime type, and `string` and `string?` are both `System.String`. The CLR does not check anything. The annotations live in metadata so that the compiler can read them across assemblies, which is why the feature works at all across NuGet packages, but nothing enforces them when the code runs.

The docs name two holes themselves, under "Known pitfalls", and call them limitations of the static analysis rather than bugs in your code:

```csharp
public struct Student
{
    public string FirstName;
    public string? MiddleName;
    public string LastName;
}

public static class Pitfalls
{
    public static void Show()
    {
        Student s = default;              // no warning, FirstName and LastName are null
        string[] values = new string[3];  // no warning, every element is null

        Console.WriteLine(s.FirstName is null);   // True
        Console.WriteLine(values[0] is null);     // True
    }
}
```

That builds with zero warnings on .NET 9 with nullable fully enabled, and prints `True` twice. Two fields and three array slots, all typed non-nullable, all holding `null`, and the compiler had nothing to say. There is no equivalent in Rust, because there is no way to conjure a `String` out of zeroes: `vec![String::new(); 3]` needs a real value to clone, and a struct with a `String` field cannot be produced without one.

Three more differences that matter day to day. Warnings are warnings, so a codebase can ship with hundreds of them. The null-forgiving `!` operator silences any of them with one character and no justification required. And the analysis does not trace into method bodies, so a helper that checks for null teaches the compiler nothing unless you annotate it with `[NotNullWhen]` or a sibling from the [nullable analysis attributes](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis).

In Rust none of that applies, because `Option` is a type rather than an annotation. `match` exhaustiveness is a compile error, not a warning. There is no `!`. There is no unannotated third-party crate whose optionality is unknown.

Where C# is genuinely ahead: nullable reference types were retrofitted onto twenty years of existing code, incrementally, file by file, with a per-project or per-file switch. Rust could never have done that, and if it had needed to, `Option` would not exist. `Nullable` for value types has been sound since C# 2.0 and needs no defense at all. And for deep member access, `a?.b?.c ?? d` really is nicer than the equivalent chain of `and_then` calls. Language-level syntax beats combinators when the shape is common enough to deserve syntax.

## Working with it without drowning in match

`if let` handles the one-case version:

```rust
if let Some(server) = find_server(7) {
    println!("{}", server.hostname);
}
```

`let else` handles the early-return version, which is the shape most guard clauses want:

```rust
let Some(server) = find_server(7) else {
    return Err(ConfigError::Missing { key: "server" });
};
// server is a plain Server from here on
```

The `else` block must leave that path with `return`, `break`, `continue`, or a panic. If execution reaches the comment, `server` is available as a plain value. Older code often uses a `match` for the same job.

You can also chain `let` bindings with `&&` and use earlier bindings later in the condition. This next form requires Rust 1.88 or later and the Rust 2024 edition:

```rust
if let Some(server) = find_server(7)
    && let Some(tls) = server.tls_config()
    && tls.is_valid()
{
    // ...
}
```

**When reading an older codebase**

[`let else` stabilized in Rust 1.65](https://blog.rust-lang.org/2022/11/03/Rust-1.65.0/) in November 2022. [Let chains arrived in Rust 1.88](https://blog.rust-lang.org/2025/06/26/Rust-1.88.0/) in June 2025 and require the 2024 edition. A project using the 2021 edition needs nested conditions or another equivalent form for the chained example.

And there is a combinator for almost anything you would otherwise write by hand:

```rust
let port = find_server(7)
    .map(|s| s.port)             // Option<Server> to Option<u16>
    .unwrap_or(5432);            // default if None

let name = find_server(7)
    .filter(|s| s.is_healthy())  // Some only if the predicate holds
    .map(|s| s.hostname)
    .unwrap_or_else(|| expensive_default());   // closure runs only on None

let region = find_server(7)
    .and_then(|s| s.region)      // map would give Option<Option<Region>>; this does not
    .unwrap_or_default();        // Default::default() on None
```

The mapping to LINQ is close enough to be useful: `map` is `Select`, `and_then` is `SelectMany`, `filter` is `Where`, `unwrap_or` is `FirstOrDefault` with a supplied default. The difference is that these are ordinary inherent methods on an ordinary enum rather than extension methods over `IEnumerable`, so there is no sequence and no deferred execution underneath, and `Result` has many analogous combinators, though its method set is not identical. Prefer `unwrap_or_else` over `unwrap_or` when the default costs anything, because `unwrap_or` evaluates its argument eagerly. Clippy has a lint for the case where it matters, `or_fun_call`, which fires when you pass a function call to `unwrap_or` instead of deferring it.

## Converting between Option and Result

The two types are the same shape with different meaning, so the conversions are cheap and you will use them constantly.

```rust
let server = find_server(7)
    .ok_or(ConfigError::Missing { key: "server" })?;   // Option to Result, then propagate

let server = find_server(7)
    .ok_or_else(|| ConfigError::Missing { key: "server" })?;  // lazy variant

let maybe: Option<Settings> = load_settings("app.toml").ok();   // Result to Option, discard why

let flipped: Result<Option<u16>, ParseIntError> =
    maybe_port_text.map(|t| t.parse::<u16>()).transpose();      // Option<Result> to Result<Option>
```

The last line uses `transpose` to keep two questions separate: was a port supplied, and was it valid?

| `maybe_port_text` | Result after parsing and `transpose()` | Meaning |
| --- | --- | --- |
| `None` | `Ok(None)` | No port was supplied. |
| `Some("5432")` | `Ok(Some(5432))` | A valid port was supplied. |
| `Some("eighty")` | `Err(ParseIntError)` | A value was supplied, but parsing failed. |

Turning the parse result into `.ok()` too early would erase that last distinction. A missing optional setting and a misspelled setting often deserve different responses.

`?` works on `Option` too, but only inside a function that itself returns `Option`. Use it in a `Result`-returning function and the compiler tells you precisely what to do:

```text
error[E0277]: the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result`
  --> src/config.rs:31:41
   |
28 | fn parse_port(raw: &str) -> Result<u16, ConfigError> {
   | -------------------------------------------------- this function returns a `Result`
...
31 |     let (_, value) = raw.split_once('=')?;
   |                                         ^ use `.ok_or(...)?` to provide an error compatible with `Result<u16, ConfigError>`
```

The label is the fix. This is not the generic trait error dressed up: the wording is a hand-written special case in `core`, attached to `FromResidual` with `rustc_on_unimplemented`, with its own message and its own suggested label for each direction of the mistake. Somebody decided this confusion was worth its own paragraph. The underlying error is the same one a C# habit produces: you reached for the propagation operator on a lookup that has no reason attached, and the type system is asking you to supply the reason.

## It costs nothing, and that is mostly not a figure of speech

The obvious worry is that wrapping every optional value in an enum adds a tag byte and a branch.

The simplified model is that `Option` is a tag plus a payload, sized to hold the larger case and aligned. That model is correct for `Option<i32>`: `i32` has alignment 4 and every 32-bit pattern is a legitimate integer, so the tag needs its own space and alignment rounds the total to 8 bytes. Twice the size for the same number. That is the honest answer for plain integers.

For pointer-like types the model is wrong, and deliberately so. The compiler uses an invalid bit pattern inside the payload as the `None` marker. A `Box`, a `&T`, a `NonNull` and a function pointer can never be null, so null is free to mean `None`. This is the null pointer optimization, and the exact guarantee is [written down in the standard library](https://doc.rust-lang.org/std/option/index.html). Rust guarantees that `Option` has the same size, alignment and function-call ABI as `T` for this list:

- `Box` where `U: Sized`, specifically only `Box`
- `&U` and `&mut U` where `U: Sized`
- `fn` and `extern "C" fn`
- `num::NonZero` types
- `ptr::NonNull` where `U: Sized`
- a `#[repr(transparent)]` struct wrapping any of the above

For those, transmuting a `T` into `Option` is defined behavior, and for the cases the docs mark, an all-zero byte pattern is `None`. That is what makes `Option>` usable directly as a nullable pointer across an FFI boundary with no wrapper.

The general mechanism is called niche optimization, and it is broader than the guarantee. `bool` occupies one byte but only two of its 256 patterns are valid, so `Option<bool>` fits in one byte using a spare pattern as `None`. Nested optionals can keep doing this until the niches run out.

The distinction that matters: the list above is a promise the standard library makes and will keep. Everything else is an optimization the compiler currently performs on the default `repr(Rust)` layout, which the [Rustonomicon](https://doc.rust-lang.org/nomicon/repr-rust.html) is clear gives you no layout guarantees at all. Rely on the list. Do not rely on `size_of` results you measured once, unless the type is `#[repr(C)]` and you have read the rules.

You can watch it yourself:

```rust
use std::mem::size_of;

fn main() {
    println!("i32                {}", size_of::<i32>());
    println!("Option<i32>        {}", size_of::<Option<i32>>());
    println!("Box<i32>           {}", size_of::<Box<i32>>());
    println!("Option<Box<i32>>   {}", size_of::<Option<Box<i32>>>());
    println!("&i32               {}", size_of::<&i32>());
    println!("Option<&i32>       {}", size_of::<Option<&i32>>());
    println!("String             {}", size_of::<String>());
    println!("Option<String>     {}", size_of::<Option<String>>());
}
```

On a 64-bit target the pointer-shaped rows come out equal on both sides, and only `Option<i32>` is larger than the thing it wraps. `String` is three words, a pointer plus a length plus a capacity, and its pointer is non-null, so `Option` is also three words. Amos has a [byte-level walkthrough with the disassembly](https://fasterthanli.me/articles/peeking-inside-a-rust-enum) if you want to see the generated code rather than the sizes.

The branch is the other half of the worry, and it is the same branch you were already writing. `Option>` compiles to a null check. You wrote that null check by hand in C#, or the JIT inserted it for you and then usually elided it. The difference is not the instruction. It is that the compiler knows the check happened.

## Option or Result

Use `Option` when absence is normal and carries no explanation. A cache lookup missed. A list was empty. A configuration key was not set and has a default. Nobody needs to know why, because there is no why.

Use `Result` when absence is a failure with a reason worth propagating. The file did not open, and the caller should know whether that was permissions or a missing path.

A workable test: if the caller might reasonably want to log or branch on the reason, it is a `Result`. If the only sensible response to `None` is a default or a different code path, it is an `Option`.

Reaching for `Option` where the caller will immediately want to know what went wrong is the most common design mistake here. `ok_or` exists precisely because people notice it one layer too late, and it is a cheap fix at the boundary. The reverse mistake, a `Result` whose error type carries no information anyone will read, is rarer but worse. `Result` is an `Option` with extra typing. Clippy's `result_unit_err` fires on public functions that return it and tells you to define a real error type.

## Twenty modules in, the shape you converge on

A larger service often uses several layers of error types. Leaf modules expose specific failures; outer modules wrap or translate them; the HTTP boundary maps errors to responses. Exhaustiveness checking applies to the variants actually matched. Adding a nested error does not force a new HTTP decision if an outer arm already handles that whole category. That mapping still needs deliberate review.

The place it gets expensive is the mid-layer wrapping. Ten modules deep, you are writing conversions that only exist to move a value from one enum to another. Boxing into `anyhow` earlier removes the boilerplate and removes the exhaustive `match` at the top with it. That is a real trade and reasonable people land in different places. The defensible default: keep typed errors wherever a caller branches on the reason, and box everywhere else.

On the `Option` side, the scale effect is quieter and mostly about deserialization. Once every optional field in a config struct is an `Option`, you get a struct where half the fields are optional and the code downstream is a forest of `unwrap_or`. The fix is the same one you would apply in C#: parse into a permissive shape once, validate into a strict shape with no optionals, and let everything after that point be total. Rust just makes the boundary between the two shapes visible in the type, which means the day someone adds a field they have to say which side of the boundary it lives on.

## Checking yourself

**Why does `?` need a `From` implementation, and what does it call it on?**
`?` on an `Err` returns `Err(From::from(e))`, converting the inner error type into the function's declared error type. Without a `From` implementation from the source error to your error, the conversion has nothing to call, and you get E0277, reported as the `?` operator failing to convert the error to your declared type.

**A function returns `Option` and callers keep asking why it was `None`. What changed, and what is the fix?**
Absence stopped being uninteresting and became a failure with a reason. Change the return type to `Result` with an enum naming the reasons, or convert at the boundary with `ok_or` if the inner function genuinely has no more information.

**Your crate compiles with `panic = "abort"` in the release profile. Name two things that behave differently.**
Destructors no longer run during a panic, so anything relying on `Drop` for cleanup or flushing on the failure path silently stops happening, and `catch_unwind` can no longer recover. Binaries also get smaller because the landing pad code is not emitted.

**Is `Option<u64>` the same size as `u64`, and why does the answer differ for `Option>`?**
No. `u64` has no unused bit pattern to represent absence, so `Option<u64>` needs extra storage; 16 bytes is a common measured layout, not a portable guarantee. For `U: Sized`, the standard library guarantees that `Option>` with the global allocator has the same size, alignment, and calling ABI as `Box`, using the null representation for `None`.

Previous: [Errors are values, and you have to look at them](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-result-vs-csharp-exceptions.md)
Next: [Interior mutability, or breaking the rules on purpose](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-interior-mutability-rc-refcell.md)
