FAQ - Help and questions

How do I port a C# application to Rust? What maps to what?

#porting#csharp#dotnetpublished 0 replies1 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Classes become structs with impl blocks, interfaces become traits, exceptions become Result, null becomes Option, and LINQ becomes iterator adapters. NuGet packages are replaced by crates. Port the data types first, then the behaviour, and compare the old and new output on the same inputs.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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 methodsstruct plus an impl block
interfacetrait
class inheritancecomposition, traits with default methods, or an enum (see the thread on classes and inheritance)
null, nullable referenceOption<T>
throw / try / catchResult<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 / IDisposableDrop: cleanup is automatic when the value goes out of scope
stringString (owned) and &str (borrowed), both UTF-8
async / await, Taskasync / .await and futures, run by a library such as Tokio
properties ({ get; set; })plain fields, or methods when logic is needed
NuGet packagecrate from crates.io (Cargo)
generics with constraints (where T : IShape)generics with trait bounds (T: Shape)
Console.WriteLineprintln!
src/main.rsrust
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(())
}
text
nobody
total area 15.71
2.5
not a number: abc
Error: Empty

How to do it#

  1. Port the data types first (classes with only fields, DTOs, enums). They are the easiest, and every other part depends on them.
  2. Replace each null with Option, and each thrown exception with a Result return, as in the program above.
  3. Replace inheritance with composition, traits or enums; this is the one design change that cannot be done line by line.
  4. 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.
  5. 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; use Result for errors you expect.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet