Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 2 of 16 · Part I, Foundations

Reading Rust when you already know C#

by Zeeshan AdilUpdated 22 min read
Listen to this articleRust Syntax for C# Developers: A Decoder Ring 22 min · read by an AI voice
0:00 / 22:00

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.

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 ->.

Code
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 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.

Code
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.

Code
fn add(a: i32, b: i32) -> i32 {
    a + b;
}
Code
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.

Code
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, 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.

Code
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 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<T> parameters for genuinely optional values; generic parameters like impl Into<String> 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.

Code
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.

Code
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.

Code
#[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));
    }
}
Code
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. 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.

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

Change nothing else, and the build stops.

Code
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.

Code
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.

Code
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:

Code
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.

Code
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));
Code
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 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 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:

Code
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, and tests often live in a separate project. The .NET SDK also includes dotnet format and supports built-in and additional analyzers.

The Cargo equivalent, following the package layout Cargo assumes by convention:

Code
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, 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:

Code
[package]
name = "core"
version = "0.1.0"
edition = "2024"

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

[dev-dependencies]
proptest = "1"

The rest of the decoder ring

C#RustWorth knowing
class (heap, reference)struct plus Box when you want the heapNo class and struct split. Heap placement is a choice at the use site
struct (value)structThe default in Rust
interfacetraitImplementable for foreign types, within the orphan rule
enum (named integer)enum (tagged union)Closed set, carries data, matched exhaustively
abstract classtrait plus compositionNo inheritance of state anywhere in the language
IEnumerable<T>IteratorBoth support lazy pipelines; allocation and optimization depend on the operations used
List<T>Vec<T>Same growable-array idea, same amortized push
Dictionary<K,V>HashMap<K,V>Rust's default hasher is chosen for HashDoS resistance and can be replaced; the algorithm may change
stringString and &strOwned and borrowed. Next chapter
nullOption<T>A type, not a value
exceptionsResult<T, E>Errors are return values
using / IDisposableDropAutomatic cleanup at drop points in ordinary execution; destructors are not guaranteed in every situation
lockMutex<T>The lock owns the data
Task<T>FutureRust futures do nothing until polled
Span<T>&[T]A slice is an ordinary type. No ref struct rules to work around
internalpub(crate)Privacy is per-module, not per-assembly
assemblycrateCompilation unit in both
.csproj and .slnCargo.toml and workspaceOne lock file and one target dir per workspace
nuget.orgcrates.iocargo add rather than dotnet add package
unsafeunsafeNarrower 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.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.