Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
C# to Rust Cheat Sheet

Thanks to @seejee for making this for me!!!

C# to Rust Cheat Sheet

The goal of this is to have an easily-scannable reference for the most common syntax idioms in C# and Rust so that programmers most comfortable with C# can quickly get through the syntax differences and feel like they could read and write basic Rust programs.

What do you think? Does this meet its goal? If not, why not?

Variables

C#:

var foo = 1;
var bar = "hi";
var somethingThatVaries = 2;
somethingThatVaries += 1;

Rust:

let foo = 1i;
let bar = "hi";
let mut something_that_varies = 2;
something_that_varies += 1;

Functions

C#:

// Function definition: takes an integer argument, returns an integer
static int DoSomething(int some_argument)
{
  return some_argument + 1;
}

// Function use
var results = DoSomething(3);

Rust:

// Function definition: takes an integer argument, returns an integer
fn do_something(some_argument: int) -> int {
    some_argument + 1 // no semicolon in implicit return statements
}

// Function use
let results = do_something(3);

Conditionals

C#:

if (x == 3)
{
  // ...
}
else if (x == 0)
{
  // ...
}
else
{
  // ...
}
// Or using a switch:
switch(x) {
  case 3:
    // ...
    break;
  case 0:
    // ...
    break;
  default:
    // ...
    break;
}

Rust:

if x == 3 {
    // ...
} else if x == 0 {
    // ...
} else {
    // ...
}

More commonly used in Rust is pattern matching, which gives you other benefits:

match x {
    3 => {
        // ...
    },
    0 => {
        // ...
    },
    _ => {
        // ...
    }
}

Output to the screen

C#:

var x = 5;
System.Console.WriteLine("x has the value {0}", x);

Rust:

let x = 5;
println!("x has the value {}", x);

Lists of variable size

I'm not saying the word "array" on purpose :) This is how to do Arrays that can grow in size.

C#:

var i = new List<String>() { "a", "b", "c" };
i.Add("d");
Console.WriteLine(i[1]); // outputs b

Rust:

let i = vec!["a", "b", "c"];
i.push("d");
println!("{}", i[1]); // outputs b

Iterating over the elements in a list

C#:

var i = new List<String>() { "a", "b", "c" };

foreach(var j in i) {
  Console.WriteLine(j);
}

i.ForEach((j) => Console.WriteLine(j));

Rust:

let i = vec!["a", "b", "c"];
for j in i.iter() {
    println!("{}", j);
}

Tests

C#: (NUnit)

using NUnit.Framework;

[TestFixture]
public class SomeTestClass
 {
   [Test]
   public void SomeTest()
    {
      Assert.AreEqual(1, 1); //will pass
      Assert.AreEqual(1, 2); //will fail
    }
  }
}

Rust:

#[test]
fn some() {
    assert!(true); // will pass
    assert_eq!("expected", "actual"); // will fail
}

Encapsulation of data + behavior

I'm not saying the word "object" on purpose :)

C#:

class Highway {
  public int Length     {get; private set;}
  public int SpeedLimit {get; private set;}

  public Highway(int length, int speedLimit) {
    this.Length = length;
    this.SpeedLimit = speedLimit;
  }
  
  public int TimeToTravel() {
    return Length / SpeedLimit;
  }
}

new Highway(325, 65).TimeToTravel(); // returns 5

Rust:

struct Highway {
    length: int,
    speed_limit: int,
}

impl Highway {
    fn time_to_travel(&self) -> int {
        self.length / self.speed_limit
    }
}

Highway { length: 325, speed_limit: 65 }.time_to_travel() // returns 5
@matthewjberger
Copy link

matthewjberger commented Dec 30, 2016

Very useful reference, although I noticed that the line under 'Lists of variable size' is missing a 'mut' keyword:

let i = vec!["a", "b", "c"];
i.push("d");

should be:

let mut i = vec!["a", "b", "c"];
i.push("d");

@HIMISOCOOL
Copy link

HIMISOCOOL commented Jul 1, 2017

awesome but I think its important to note that

let foo = 1i;
let bar = "hi";

is also equivalent to const (in some cases)

const int foo = 1;
const string bar = "hi";

though you cant have

const var

or

const

like in typescript

you could also do something like this
https://gist.github.com/HIMISOCOOL/fe02fc1030fbc55f0d07376faba12d6d
to show how OO works in rust.
I'm only new to rust so somethings in the rust might be wrong.
This took forever for me to think over when I started rust because its such a shock to the system that you cant inherit things.

@seriouz
Copy link

seriouz commented Nov 26, 2019

The last example could be written in C# as

class Highway {
    public int Length = 0;
    public int SpeedLimit = 0;
    
    public int TimeToTravel() {
        return Length / SpeedLimit;
    }
}
new Highway{Length = 325, SpeedLimit = 65}.TimeToTravel()

@AqlaSolutions
Copy link

AqlaSolutions commented Dec 3, 2020

The last example doesn't contain getters for the fields.

@danielleiszen
Copy link

danielleiszen commented Apr 4, 2022

The last example could be written in C# as

class Highway {
    public int Length = 0;
    public int SpeedLimit = 0;
    
    public int TimeToTravel() {
        return Length / SpeedLimit;
    }
}
new Highway{Length = 325, SpeedLimit = 65}.TimeToTravel()

Not true, the rust version is inmutable, this c# code is mutable even from outside of the class. However in the original example the properties also have private setters which allow the instance to mutate its state which is not allowed in the rust code. So both examples are wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment