Skip to content

Amethyst for C# developers

You already know the hard part. Amethyst runs on the CLR, uses the .NET class library and ships through NuGet. Its types are your types: an Amethyst class is a .NET class, String is System.String, and an async method returns a Task<T>.

What changes is the syntax (fewer braces, more end) and a few defaults. Semicolons are optional, and end settles the Allman versus K&R debate by making everyone equally unhappy. This page puts C# and Amethyst side by side.

C#
public static class Program
{
public static void Main()
{
Console.WriteLine("Hello, world!");
}
}
Amethyst
def main: Void
puts "Hello, world!"
end

No class to put it in. You may feel a phantom urge to type static. It passes.

Assignment declares a variable, with its type inferred. Annotate with name: Type. Names in ALL_CAPS are constants and compile to const or static readonly.

C#
var name = "Ada";
string greeting = "Hello";
const int MaxRetries = 3;
Amethyst
name = "Ada"
greeting: String = "Hello"
MAX_RETRIES = 3

Types come after names, the last expression is the return value, and a public method without a return type returns nil and compiles to void. Names are snake_case; the compiler emits PascalCase for C# callers.

C#
public int Double(int x) => x * 2;
public bool IsValid() => errors.Count == 0;
public void Log(string message)
{
Console.WriteLine(message);
}
Amethyst
def double(x: Int): Int
x * 2
end
def valid?: Bool
@errors.count == 0
end
def log(message: String)
puts message
end

A ? method must return Bool and compiles to IsValid(). A ! method, such as save!, raises on failure and compiles to Save(). It is not a negation.

Keyword parameters are declared with :: and must be passed by name. C# lets you choose; Amethyst asks you to commit.

C#
User Create(string name, string role = "user") { … }
Create(name: "Ada", role: "admin");
Create("Ada");
Amethyst
def create(name:: String, role:: String = "user"): User
end
create(name: "Ada", role: "admin")
create(name: "Ada")

property replaces { get; set; }, getter replaces { get; }, the constructor is called initialize, and you construct with .new. Static members are defined on self.

C#
public class User
{
public string Name { get; set; }
public int Age { get; }
public User(string name, int age)
{
Name = name;
Age = age;
}
public static User Guest() => new User("Guest", 0);
}
var user = new User("Ada", 36);
Amethyst
class User
property name: String
getter age: Int
def initialize(name: String, age: Int)
@name = name
@age = age
end
def self.guest: User
User.new("Guest", 0)
end
end
user = User.new("Ada", 36)
C# Amethyst
class Admin : User class Admin < User
interface IShape protocol Shape, adopted with implements Shape
Extension methods extension class String
Default interface methods Mixins, with include
List<T> List[T]
where T : IComparable<T> [T < Comparable[T]]
where T : class, new() where T: class, T: new
using System.Text; use System::Text
namespace MyApp.Models; namespace MyApp::Models
[Serializable] @[Serializable]
user?.Name user&.name
x => x * 2 { |x| x * 2 } or ->(x: Int) { x * 2 }
out var result out result
async Task<string> async def …: String
int* Pointer[Int]

Nullable reference types, except the compiler means it: types are non-nullable by default, String? opts in, and using a nullable value unchecked is an error, not a warning. A nil check narrows the type inside the branch.

C#
User? user = FindUser(id);
if (user != null)
{
Console.WriteLine(user.Name);
}
var city = user?.Address?.City;
Amethyst
user = find_user(id) # User?
if user
puts user.name # narrowed to User
end
city = user&.address&.city # String?

if accepts only a Bool or a nullable value. For code that calls into older, unannotated C# libraries, null_safety off at the top of a file restores C#’s pre-nullable behaviour. See Types.

Collections get Ruby-style methods from Enumerable[T], including every .NET type that implements IEnumerable<T>.

C#
var names = users
.Where(u => u.Active)
.OrderBy(u => u.Name)
.Select(u => u.Name)
.ToList();
Amethyst
names = users.select(&:active?).sort_by(&:name).map(&:name)
LINQ Amethyst
Where select (or reject for the opposite)
Select map
SelectMany flat_map
Aggregate reduce
OrderBy sort_by
GroupBy group_by
Any / All any? / all?
FirstOrDefault first (returns T?)
Take / Skip take / drop
ToList to_array

A block is a lambda you pass after the call, in { } or do … end. One difference matters: return inside a block returns from the enclosing method, not just the block. Use next to finish the current iteration. Lambdas written with -> behave like C# lambdas.

C#
User? FirstAdmin(List<User> users)
{
foreach (var user in users)
{
if (user.IsAdmin) return user;
}
return null;
}
Amethyst
def first_admin(users: Array[User]): User?
users.each do |user|
return user if user.admin? # returns from first_admin
end
nil
end

C# builds complex objects with fluent builders: methods that return this, chained until someone calls Build(). Amethyst uses blocks whose self is the builder, so a builder reads like a little language and is still checked by the compiler.

C#
var page = new HtmlBuilder()
.H1("Shopping list")
.Ul(ul => ul
.Li("Eggs")
.Li("Milk"))
.Build();
Amethyst
page = html do
h1 "Shopping list"
ul do
li "Eggs"
li "Milk"
end
end

No return this, no lambda parameter to thread through, no Build() to forget. See Type-safe builders to write your own.

The same .NET exceptions, with Ruby’s keywords. rescue sounds more heroic than catch anyway.

C#
try
{
Parse(path);
}
catch (FileNotFoundException e)
{
Log(e.Message);
}
finally
{
Cleanup();
}
Amethyst
begin
parse(path)
rescue FileNotFoundException => e
log e.message
ensure
cleanup
end

For one-liners, value = risky_method rescue fallback replaces a whole try/catch. Instead of a using statement, call use with a block: StreamReader.new(path).use do |reader| … end disposes of the reader however the block finishes. See Error Handling.

case/when is an expression, and matching on a type narrows the value in that branch.

C#
var area = shape switch
{
Circle c => Math.PI * c.Radius * c.Radius,
Rectangle r => r.Width * r.Height,
_ => 0.0,
};
Amethyst
area = case shape
when Circle then Math::PI * shape.radius ** 2
when Rectangle then shape.width * shape.height
else 0.0
end

The return type is written unwrapped; the compiler adds the Task. You may never type Task<IReadOnlyDictionary<string, List<int>>> again. Not here, anyway.

C#
public async Task<string> FetchAsync(string url)
{
var response = await http.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
Amethyst
async def fetch(url: String): String
response = await http.get_async(url)
await response.content.read_as_string_async
end

Your existing assemblies work as they are. list.add finds List.Add, generics use brackets, and out/ref appear only at call sites. Going the other way, C# sees ordinary .NET types and PascalCase members. See .NET Interop for both directions.