# Reading Rust when you already know C#

> Read Rust fluently if you know C#: expressions, let and mut, structs and impl blocks, exhaustive enums, modules, and where the syntax hides a real difference.

- 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-syntax-for-csharp-engineers

Chapter 2 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 I, Foundations.

This chapter is a decoder for the examples ahead. Focus first on expressions, `let`, `mut`, structs, and `match`. The solution layout and comparison details are useful references when you start your own project.

Some Rust syntax will feel familiar if you know C#. Slow down when a familiar-looking expression changes how the program behaves, particularly when it moves a value or chooses between enum variants.

## Expressions, and why almost everything is one

A function is `fn`, types come after the name, and the return type comes after `->`.

```rust
fn add(a: i32, b: i32) -> i32 {
    a + b
}
```

Note the missing `return` and the missing semicolon. Rust is expression-oriented: the last expression in a block is the block's value. [The Reference's chapter on statements](https://doc.rust-lang.org/reference/statements.html) covers the other half, which is that adding a semicolon turns an expression into a statement whose value is discarded.

That rule is why `if`, `match`, `loop` and plain blocks all produce values.

```rust
let category = if bytes > 1_000_000 { "large" } else { "small" };

let timeout_secs = match tier {
    Tier::Free => 5,
    Tier::Pro => 30,
    Tier::Enterprise => 120,
};
```

C# has been walking toward this for years. Expression-bodied members with `=>`, the conditional operator, switch expressions in C# 8: all of it exists because assigning once beats declaring then assigning in branches. Rust started there, so the pattern is universal rather than available in particular syntactic positions.

The practical consequence is that you almost never write the C# shape of declare-uninitialized-then-fill-in-branches. You write a `let` bound to a `match`. The practical hazard is a stray semicolon, and it is worth seeing once, because the message is not obviously about semicolons.

```rust
fn add(a: i32, b: i32) -> i32 {
    a + b;
}
```

```text
error[E0308]: mismatched types
 --> src/main.rs:1:27
  |
1 | fn add(a: i32, b: i32) -> i32 {
  |    ---                    ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail expression
  |
help: remove this semicolon to return this value
  |
2 -     a + b;
2 +     a + b
  |
```

The `help` line at the bottom is the whole diagnostic. `()` is the unit type, which has one value, also written `()`. In this function, the semicolon discards the expression's value, so the body evaluates to unit instead of `i32`. It plays a role similar to C#'s `void`, but it is a regular type and value in Rust.

## let, mut, and shadowing

Variables are `let`, and they are immutable unless you say otherwise.

```rust
let count = 5;          // cannot be reassigned
let mut total = 0;      // can be
```

`readonly` in C# is opt-in and lands on fields, struct declarations and struct members. Rust flips the default and attaches it to the binding rather than the type. That distinction matters: `mut` is not part of `i32`, it is a property of this particular name, so the same value can be immutable in one function and mutable in the next.

For ordinary locals C# gives you `const`, which only covers compile-time constants of a handful of types, and nothing else. There is no way to say "this `HttpClient` local never gets reassigned", and after a while in Rust you notice you were relying on that guarantee informally the entire time.

Reassigning without `mut` gets you [E0384](https://doc.rust-lang.org/error_codes/E0384.html), `cannot assign twice to immutable variable`, and the compiler points at the original binding and suggests adding `mut`.

Then there is shadowing, which looks like a mistake and is idiomatic.

```rust
let port = "5432";
let port: u16 = port.parse().expect("port must be a number");
```

The second `let` creates a new binding with the same name and a different type. The earlier binding is hidden by the new one; any value it owned is still subject to Rust's drop rules. The Rust Book's [section on shadowing](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing) makes the case: you avoid inventing `portStr` and `portParsed`, and because it is a new binding rather than an assignment, immutability survives. C# forbids this, and forbids it for a good reason, which is that in C# a shadowed name usually means somebody made a typo. In Rust, parse-and-rebind is a named pattern with a purpose.

## Functions, and three things C# has that Rust does not

`fn` takes parameters with declared types and returns one value. That is the whole story, and the missing pieces will annoy you.

There is no overloading. There are no default parameter values. There are no named arguments. Coming from a language where `Log(string)`, `Log(string, Exception)` and `Log(string, Exception, LogLevel)` are one method name, this feels like a step backward, and in pure API ergonomics it is one.

What replaces them: distinct constructor names by convention, so `Vec::new` and `Vec::with_capacity` rather than an overload; `Option` parameters for genuinely optional values; generic parameters like `impl Into` so one function accepts several input types; and the builder pattern for anything with more than three or four knobs. The result is more verbose at the definition and often clearer at the call site, because `with_capacity(1024)` says what `new(1024)` does not.

## Structs, impl blocks, and the three forms of self

Structs hold data. `impl` blocks hold behavior. They are separate declarations, and a type may have several `impl` blocks.

```rust
struct Server {
    hostname: String,
    port: u16,
}

impl Server {
    fn new(hostname: String, port: u16) -> Self {
        Server { hostname, port }
    }

    fn address(&self) -> String {
        format!("{}:{}", self.hostname, self.port)
    }

    fn set_port(&mut self, port: u16) {
        self.port = port;
    }

    fn into_hostname(self) -> String {
        self.hostname
    }
}
```

`Self` with a capital S is the type. `self` lowercase is the instance, and it appears explicitly as the first parameter, which is closer to Python than to C#. `new` is a naming convention for an associated function, not a special constructor keyword. You can also use names such as `connect` or `open` when they describe the operation better.

The three forms of `self` are the part to memorize, because they put information in a signature that C# cannot put there.

`&self` borrows the instance to read. The caller keeps it, and no code can reach the fields through that reference to write them. The closest C# analogue is an instance method you have promised will not change state, except here the promise is checked. The escape hatch is interior mutability. `Cell`, `RefCell`, `Mutex` and the atomics all let you write through a shared reference: `Cell` through methods that replace or retrieve values without giving out an ordinary reference to its contents, `RefCell` through runtime borrow checks, and `Mutex` through synchronization. A conflicting `RefCell` borrow can panic; a mutex may block while another thread holds it. So `&self` means "no direct field writes", not "nothing changes".

`&mut self` borrows the instance exclusively. The caller retains ownership and the method may mutate through the exclusive borrow. While that borrow is active, safe code cannot use conflicting references to the same data; references can exist outside that active period, and a method may also reborrow the data.

`self` consumes the instance. The caller hands it over and cannot use it afterward. There is no C# equivalent, and this is the one that pays for itself.

Consider a type wrapping something you must close exactly once. In C# the standard shape is `IDisposable`, a `_disposed` flag, and `ObjectDisposedException` for anyone who uses it afterward.

```csharp
sealed class Channel : IDisposable
{
    private bool _disposed;

    public void Send(string message)
    {
        if (_disposed) throw new ObjectDisposedException(nameof(Channel));
        // ...
    }

    public void Dispose() => _disposed = true;
}
```

Those guards check the object's state at run time. A Rust method `fn close(self)` can express a different design: for a non-`Copy` channel owned by the caller, `channel.close()` consumes that value, so using that same value afterward is a compile error. Shared handles or clones can still exist, and the implementation must define what closing them means; consuming one handle does not by itself guarantee that an external resource closes exactly once.

That is a recurring Rust design choice: put the invariant a type can express into the signature, and leave the remaining checks at the boundary where they belong.

## Enums, and the exhaustiveness that follows

Enums are the piece that looks familiar and is not. A C# enum is a named integer. A Rust enum is a tagged union: each variant is its own shape carrying its own data, and the set of variants is the type.

Here is a complete program. Save it as `src/main.rs` in a fresh `cargo new` project and run `cargo run`.

```rust
#[derive(Debug)]
enum ConnectionState {
    Idle,
    Connecting { attempt: u32 },
    Active { peer: String },
    Failed(std::io::Error),
}

fn describe(state: &ConnectionState) -> String {
    match state {
        ConnectionState::Idle => "idle".to_string(),
        ConnectionState::Connecting { attempt } => format!("connecting, attempt {attempt}"),
        ConnectionState::Active { peer } => format!("active with {peer}"),
        ConnectionState::Failed(err) => format!("failed: {err}"),
    }
}

fn main() {
    let states = vec![
        ConnectionState::Idle,
        ConnectionState::Connecting { attempt: 3 },
        ConnectionState::Active { peer: String::from("db-1:5432") },
        ConnectionState::Failed(std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            "handshake timed out",
        )),
    ];

    for state in &states {
        println!("{}", describe(state));
    }
}
```

```text
idle
connecting, attempt 3
active with db-1:5432
failed: handshake timed out
```

If you have used F# discriminated unions this is that, and [C# 15 adds union types and closed hierarchies](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-15). The examples here use .NET 9 and C# 13, so keep that version difference in mind. `Option` and `Result`, which you will use in every file you write, are declared in the standard library as ordinary enums rather than built into the language.

`match` takes them apart, and `match` is exhaustive. Now add a variant, the way you would in a real system the week somebody asks for graceful shutdown.

```rust
#[derive(Debug)]
enum ConnectionState {
    Idle,
    Connecting { attempt: u32 },
    Active { peer: String },
    Failed(std::io::Error),
    Draining(u32),
}
```

Change nothing else, and the build stops.

```text
error[E0004]: non-exhaustive patterns: `&ConnectionState::Draining(_)` not covered
  --> src/main.rs:11:11
   |
11 |     match state {
   |           ^^^^^ pattern `&ConnectionState::Draining(_)` not covered
   |
note: `ConnectionState` defined here
  --> src/main.rs:2:6
   |
2  | enum ConnectionState {
   |      ^^^^^^^^^^^^^^^
...
7  |     Draining(u32),
   |     -------- not covered
   = note: the matched value is of type `&ConnectionState`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
   |
15 ~         ConnectionState::Failed(err) => format!("failed: {err}"),
16 +         &ConnectionState::Draining(_) => todo!()
   |

For more information about this error, try `rustc --explain E0004`.
```

Exact wording drifts a little between compiler versions, but the structure is stable: the uncovered pattern, the enum definition with the offending variant underlined, and a suggested arm. In a real codebase this fires once per incomplete `match`, and the build output is a work list with file names and line numbers. Every place that needs to think about draining is in front of you before the code runs.

## Why C# cannot do this, and it is not for lack of trying

C# has pattern matching and switch expressions, so the shape looks the same. The difference is enforcement, and the reason is structural rather than a missing feature.

Write the closest C# equivalent, a closed-looking hierarchy of records.

```csharp
abstract record ConnectionState;
sealed record Idle : ConnectionState;
sealed record Connecting(uint Attempt) : ConnectionState;
sealed record Active(string Peer) : ConnectionState;
sealed record Failed(Exception Error) : ConnectionState;
sealed record Draining(uint Remaining) : ConnectionState;

static string Describe(ConnectionState state) => state switch
{
    Idle => "idle",
    Connecting c => $"connecting, attempt {c.Attempt}",
    Active a => $"active with {a.Peer}",
    Failed f => $"failed: {f.Error.Message}",
};
```

On .NET 9.0.306 that compiles, with a warning.

```text
warning CS8509: The switch expression does not handle all possible values of its
input type (it is not exhaustive). For example, the pattern '_' is not covered.

Build succeeded.
    1 Warning(s)
    0 Error(s)
```

And then it ships, and then:

```text
Unhandled exception. System.Runtime.CompilerServices.SwitchExpressionException:
Non-exhaustive switch expression failed to match its input.
Unmatched value was Draining { Remaining = 3 }.
```

With the default warning configuration, this can build and then throw at runtime. A project can configure that warning as an error to make the build fail. Both behaviors above are reproducible with `dotnet new console` on that SDK, and both messages are stable text you can look up: CS8509 in the compiler messages and `SwitchExpressionException` in the BCL.

Notice that all five records are in one file and every leaf is `sealed`. It does not help. C# has no closed-hierarchy exhaustiveness check, and the reason is that the type system is open in two ways at once. Mark `ConnectionState` public and any assembly referencing yours can derive from it, so the compiler cannot enumerate the subtypes even in principle. And `null` is a legal value of every reference type, so a switch over reference patterns always carries one more case than you wrote. Roslyn does not special-case the situation where you happen to have closed the set by hand.

The same thing happens with plain enums, and there it is sharper, because you cannot fix it by being careful. A C# enum is a named integer, so a value outside the named set is still a legal value of the type.

```csharp
enum Level { Debug, Info, Warn }

static string Name(Level l) => l switch
{
    Level.Debug => "debug",
    Level.Info => "info",
    Level.Warn => "warn",
};

Console.WriteLine(Name((Level)99));
```

```text
warning CS8524: The switch expression does not handle some values of its input type
(it is not exhaustive) involving an unnamed enum value. For example, the pattern
'(Level)3' is not covered.
```

You covered every member of the enum and the compiler still cannot promise you anything, because `(Level)99` exists. At run time it throws the same `SwitchExpressionException`. A Rust enum is closed: the variant list is the type, `ConnectionState` has no representation outside its declared variants, and the compiler can therefore reason about the whole set.

The closed world does create a real problem for library authors, and Rust has a specific answer. If your public enum is closed, adding a variant breaks downstream exhaustive matches that list the old variants, making it a breaking change for those consumers. So a library can write `#[non_exhaustive]` on the enum, which forces external crates to include a wildcard arm while leaving matches inside the defining crate fully checked. Exhaustiveness where you own the code, forward compatibility where you do not. It is the kind of detail that tells you a feature has survived contact with real users.

The trap here is specifically a C# one. When a `match` will not compile, the fastest way out is `_ => {}`, and the habit transfers directly from `default:` in a `switch`. Resist it on your own domain types. A wildcard arm is a promise that every future variant can be handled identically, which is almost never true, and the moment you write it you have converted the compile error you wanted into the run-time surprise you were trying to leave behind. Wildcards belong on genuinely open sets: integers, strings, foreign `#[non_exhaustive]` enums.

## Traits, modules, and where things live

Traits are where interfaces go. `impl Display for Server` reads as "implement `Display` for `Server`", and unlike C# you can do this for a type someone else defined. There is a limit, called the orphan rule: one of the trait or the type has to be yours, so you cannot implement `serde::Serialize` for `chrono::DateTime` from your own crate. The traits chapter is about why that matters more than it sounds.

Modules replace namespaces, `use` replaces `using`, and `pub` replaces `public`, but the underlying model differs in a way that catches people.

A C# namespace is a naming device. It has nothing to do with files, nothing to do with assemblies, and nothing to do with accessibility. Your access modifiers are `public`, `internal`, `private` and friends, and `internal` means assembly-wide.

A Rust module is a tree, and that tree is the privacy boundary. [The Reference](https://doc.rust-lang.org/reference/visibility-and-privacy.html) states the rule: everything is private by default, and a private item is reachable from the module where it is declared and from all of that module's descendants. `pub` makes an item visible to whoever can see the module. `pub(crate)` is the honest translation of `internal`. `pub(super)` exposes an item to the parent module only, and `pub(in path)` targets a named ancestor module.

Two things escape the default, and both save you typing you would otherwise expect: associated items in a `pub` trait are public, and the variants of a `pub` enum are public. You never write `pub` on a trait method or an enum variant.

The mistake to expect: writing `pub` on everything, because in a C# application assembly you write `public` on everything and the `internal` distinction rarely bites. In Rust, `pub` on an item in a library crate is a public API commitment that constrains your next semver bump. `pub(crate)` is what you meant almost every time, and it costs you nothing.

## On disk, against a dotnet solution

The two layouts encode different assumptions, and comparing them is the fastest way to see what Cargo takes over.

A .NET solution, stripped of noise:

```text
MyService.sln
Directory.Build.props
Directory.Packages.props
src/
  MyService.Api/
    MyService.Api.csproj
    Program.cs
    bin/  obj/
  MyService.Core/
    MyService.Core.csproj
    bin/  obj/
tests/
  MyService.Tests/
    MyService.Tests.csproj
    bin/  obj/
```

Each project is an assembly, each has its own `bin` and `obj`. Package versions are per-project unless you opt into [central package management](https://learn.microsoft.com/en-us/nuget/consume-packages/central-package-management), and tests often live in a separate project. The .NET SDK also includes [`dotnet format`](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-format) and supports built-in and additional analyzers.

The Cargo equivalent, following the [package layout](https://doc.rust-lang.org/cargo/guide/project-layout.html) Cargo assumes by convention:

```text
Cargo.toml           # workspace manifest
Cargo.lock           # one lock file for the whole workspace
target/              # one build directory for the whole workspace
crates/
  api/
    Cargo.toml
    src/
      main.rs        # binary crate root
      routes.rs
  core/
    Cargo.toml
    src/
      lib.rs         # library crate root
      parser.rs
    tests/
      integration.rs # each file here is its own test binary
    benches/
    examples/
```

The differences are not cosmetic.

**Package is not crate.** A package is one `Cargo.toml`. A crate is one compilation unit, roughly one assembly. A package can produce a library crate plus any number of binary crates, which is why `src/main.rs` and `src/lib.rs` can coexist and every file under `src/bin/` becomes its own executable.

**A workspace shares more than a solution does.** One `Cargo.lock` and one `target/` for the whole [workspace](https://doc.rust-lang.org/cargo/reference/workspaces.html), so members resolve against a single dependency graph instead of each project picking for itself. That is stricter than a `.sln`, which shares nothing until you opt into central package management.

Be careful about what that actually guarantees. Cargo unifies requirements that are semver compatible, so two members asking for `serde` 1.0.190 and 1.0.210 get one copy. It does not unify across incompatible majors: `rand` 0.8 and `rand` 0.9 will both be in your build, linked side by side, and a value of one is not a value of the other. The types from incompatible versions are distinct: a value from one version cannot be passed where the other version's type is expected without an explicit conversion. The versions may coexist in the build, potentially increasing binary size. .NET assembly loading and version resolution have their own rules, so the exact comparison depends on the application and load context.

**Unit tests live in the file they test.** A `#[cfg(test)] mod tests` block at the bottom of the source file is idiomatic, it compiles only under `cargo test`, and because it is a child module it can see private items. Integration tests go in `tests/`, compile as separate crates, and see only your public API. That split is a design tool: if a test in `tests/` cannot reach something, the compiler is telling you about your API surface.

**The toolchain has no seams.** `cargo build`, `cargo test`, `cargo fmt`, `cargo clippy`, `cargo doc`, `cargo add`, `cargo publish`. Cargo gives these workflows a consistent entry point; the .NET CLI also provides build, test, package, and formatting commands, with analyzer choices configured by the project.

Cargo.toml itself is short enough to read in one breath, and `[dev-dependencies]` is what you want where you would have added a test-only `PackageReference`:

```toml
[package]
name = "core"
version = "0.1.0"
edition = "2024"

[dependencies]
serde = { version = "1", features = ["derive"] }

[dev-dependencies]
proptest = "1"
```

Some Rust conventions look like noise until you know what they buy. `snake_case` for functions and variables, `CamelCase` for types, `SCREAMING_CASE` for constants, and a trailing comma on every multi-line list because it keeps diffs clean.

[rustfmt](https://rust-lang.github.io/rustfmt/) and [Clippy](https://doc.rust-lang.org/clippy/) are standard Rust toolchain components, though a particular toolchain may need them installed. Projects can configure their formatting and lint choices; the common entry points make them easy to discover. Coming from a .NET shop with an `.editorconfig` battle in its history, that alone is worth something. It is also the one place where arriving late paid off: Rust got to pick defaults after watching everyone else fight about them.

## The rest of the decoder ring

| C# | Rust | Worth knowing |
| --- | --- | --- |
| `class` (heap, reference) | `struct` plus `Box` when you want the heap | No class and struct split. Heap placement is a choice at the use site |
| `struct` (value) | `struct` | The default in Rust |
| `interface` | `trait` | Implementable for foreign types, within the orphan rule |
| `enum` (named integer) | `enum` (tagged union) | Closed set, carries data, matched exhaustively |
| `abstract class` | `trait` plus composition | No inheritance of state anywhere in the language |
| `IEnumerable` | `Iterator` | Both support lazy pipelines; allocation and optimization depend on the operations used |
| `List` | `Vec` | Same growable-array idea, same amortized push |
| `Dictionary` | `HashMap` | Rust's default hasher is chosen for HashDoS resistance and can be replaced; the algorithm may change |
| `string` | `String` and `&str` | Owned and borrowed. Next chapter |
| `null` | `Option` | A type, not a value |
| exceptions | `Result` | Errors are return values |
| `using` / `IDisposable` | `Drop` | Automatic cleanup at drop points in ordinary execution; destructors are not guaranteed in every situation |
| `lock` | `Mutex` | The lock owns the data |
| `Task` | `Future` | Rust futures do nothing until polled |
| `Span` | `&[T]` | A slice is an ordinary type. No `ref struct` rules to work around |
| `internal` | `pub(crate)` | Privacy is per-module, not per-assembly |
| assembly | crate | Compilation unit in both |
| `.csproj` and `.sln` | `Cargo.toml` and workspace | One lock file and one target dir per workspace |
| nuget.org | crates.io | `cargo add` rather than `dotnet add package` |
| `unsafe` | `unsafe` | Narrower than you think, and covered later |

That is enough to read anything below. Everything else I will explain where it appears.

## Where C# stays ahead in this chapter's material

Two places, and neither is a close call.

Function-level API ergonomics. Overloading, default parameter values and named arguments make a C# API pleasant in a way Rust currently cannot match, and the builder pattern is a workaround rather than a win. If you are designing a surface consumed by application developers rather than systems programmers, C# hands you better tools.

Discoverability of the visibility model. `internal` in a single-assembly application is one keyword with one meaning and takes about ten seconds to teach. Rust's module tree is more precise and more expressive, and it takes an afternoon and a diagram. Precision is not free.

## Checking yourself

**Why does a garbage collector's cost show up in p99 rather than in throughput?**
A brief pause can affect a small fraction of requests while contributing little to the average. Whether it changes p99, a higher percentile, or throughput depends on pause frequency, request timing, and the rest of the latency distribution. Measure both pause events and request latency.

**What sets how often the .NET collector runs, and what sets how long each collection takes?**
Allocation rate and the runtime's changing per-generation budgets influence frequency. Surviving data, heap layout, collection type, and concurrency influence duration. These are useful starting points, but they interact; use runtime measurements to find the cost in your service.

**Rust rejects a function you are certain is correct. What has the compiler actually claimed?**
That the function does not satisfy the compiler's rules. The code may be safe for reasons the compiler cannot establish, or the rejection may expose a real bug. Usually the next step is to examine the ownership design and restructure it. `unsafe` permits specific operations such as raw-pointer dereferencing; it does not turn off the borrow checker, and any safety obligation for those operations remains with the programmer.

**You add a variant to a shared enum. What happens in each language, and why?**
A Rust `match` that explicitly lists the old variants becomes incomplete when a new one is added, unless it already has a wildcard arm. In the C# examples above, the compiler emits a non-exhaustiveness warning; with default settings it can still build and throw if an unmatched value reaches the switch. You can configure the warning as an error. The record hierarchy and named-integer enum also have different possible values from a closed Rust enum.

Previous: [The trade Rust is actually making](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/the-trade-rust-is-making.md)
Next: [Where your data actually lives](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-stack-heap-box-and-strings.md)
