Answer#
C# and Rust share ideas (generics, interfaces, pattern matching), but Rust has no garbage collector, no inheritance of classes, no exceptions and no null. Most of a port is mechanical once you know the replacement for each construct. The table is the map; the program below uses each row and was compiled and run with rustc 1.93.0.
| C# | Rust |
|---|---|
class with fields and methods | struct plus an impl block |
interface | trait |
| class inheritance | composition, traits with default methods, or an enum (see the thread on classes and inheritance) |
null, nullable reference | Option<T> |
throw / try / catch | Result<T, E> and the ? operator |
List<T>, Dictionary<K, V> | Vec<T>, HashMap<K, V> |
LINQ (Where, Select, Sum) | iterator adapters (filter, map, sum) |
using / IDisposable | Drop: cleanup is automatic when the value goes out of scope |
string | String (owned) and &str (borrowed), both UTF-8 |
async / await, Task | async / .await and futures, run by a library such as Tokio |
properties ({ get; set; }) | plain fields, or methods when logic is needed |
| NuGet package | crate from crates.io (Cargo) |
generics with constraints (where T : IShape) | generics with trait bounds (T: Shape) |
Console.WriteLine | println! |
use std::collections::HashMap;
use std::fmt;
// C#: public interface IShape { double Area(); }
trait Shape {
fn area(&self) -> f64;
}
// C#: public sealed class Circle : IShape { public double Radius { get; } ... }
struct Circle {
radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
// C#: exceptions -> Result<T, E>
#[derive(Debug)]
enum ParseError {
Empty,
NotANumber(String),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::Empty => write!(f, "empty input"),
ParseError::NotANumber(s) => write!(f, "not a number: {s}"),
}
}
}
impl std::error::Error for ParseError {}
fn parse_radius(s: &str) -> Result<f64, ParseError> {
let s = s.trim();
if s.is_empty() {
return Err(ParseError::Empty);
}
s.parse().map_err(|_| ParseError::NotANumber(s.to_string()))
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
// C#: null -> Option<T>
let names: HashMap<u32, &str> = HashMap::from([(1, "Ada"), (2, "Bo")]);
let who = names.get(&3).copied().unwrap_or("nobody");
println!("{who}");
// C#: var shapes = new List<IShape> { ... }; foreach / LINQ -> iterators
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { radius: 1.0 }), Box::new(Circle { radius: 2.0 })];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("total area {total:.2}");
println!("{}", parse_radius("2.5")?);
match parse_radius("abc") {
Err(e) => println!("{e}"),
Ok(_) => unreachable!(),
}
parse_radius(" ")?; // `?` returns the error from main, like an unhandled exception ends the program
Ok(())
}nobody
total area 15.71
2.5
not a number: abc
Error: EmptyHow to do it#
- Port the data types first (classes with only fields, DTOs, enums). They are the easiest, and every other part depends on them.
- Replace each
nullwithOption, and each thrown exception with aResultreturn, as in the program above. - Replace inheritance with composition, traits or enums; this is the one design change that cannot be done line by line.
- Port the logic of one class or module at a time, with its unit tests. Run the old and the new code on the same inputs and compare the output.
- Call across the two worlds while you migrate: a Rust library can be loaded by a .NET program. The page on Rust and .NET with NuGet describes the packaging side.
Common mistakes#
- Copying class hierarchies one to one. Ask what behaviour is shared and use a trait for it.
- Using
Rc<RefCell<T>>everywhere to copy C#'s free sharing of references. First check whether one owner and borrowed references are enough. - Porting exceptions as
panic!. A panic ends the thread; useResultfor errors you expect.
Related questions#
Do I have to port the whole application at once?#
No. Port a library or a module behind an interface and keep the rest in C# until it is done.
What replaces Entity Framework or ASP.NET Core?#
There is no single replacement. Web servers are built with a framework such as axum, and database access with a crate such as sqlx; choose by what the application does.
Sources#
- The Rust Book: https://doc.rust-lang.org/book/
- Rust by Example: https://doc.rust-lang.org/rust-by-example/