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.
Hello, world
Section titled “Hello, world”public static class Program{ public static void Main() { Console.WriteLine("Hello, world!"); }}def main: Void puts "Hello, world!"endNo class to put it in. You may feel a phantom urge to type static. It passes.
Variables and constants
Section titled “Variables and constants”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.
var name = "Ada";string greeting = "Hello";const int MaxRetries = 3;name = "Ada"greeting: String = "Hello"MAX_RETRIES = 3Methods
Section titled “Methods”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.
public int Double(int x) => x * 2;
public bool IsValid() => errors.Count == 0;
public void Log(string message){ Console.WriteLine(message);}def double(x: Int): Int x * 2end
def valid?: Bool @errors.count == 0end
def log(message: String) puts messageendA ? 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.
Named arguments
Section titled “Named arguments”Keyword parameters are declared with :: and must be passed by name. C# lets you
choose; Amethyst asks you to commit.
User Create(string name, string role = "user") { … }
Create(name: "Ada", role: "admin");Create("Ada");def create(name:: String, role:: String = "user"): Userend
create(name: "Ada", role: "admin")create(name: "Ada")Classes
Section titled “Classes”property replaces { get; set; }, getter replaces { get; }, the constructor is
called initialize, and you construct with .new. Static members are defined on
self.
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);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) endend
user = User.new("Ada", 36)Translation table
Section titled “Translation table”| 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] |
Nullability
Section titled “Nullability”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.
User? user = FindUser(id);if (user != null){ Console.WriteLine(user.Name);}var city = user?.Address?.City;user = find_user(id) # User?if user puts user.name # narrowed to Userendcity = 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>.
var names = users .Where(u => u.Active) .OrderBy(u => u.Name) .Select(u => u.Name) .ToList();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 |
Blocks and lambdas
Section titled “Blocks and lambdas”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.
User? FirstAdmin(List<User> users){ foreach (var user in users) { if (user.IsAdmin) return user; } return null;}def first_admin(users: Array[User]): User? users.each do |user| return user if user.admin? # returns from first_admin end nilendType-safe builders
Section titled “Type-safe builders”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.
var page = new HtmlBuilder() .H1("Shopping list") .Ul(ul => ul .Li("Eggs") .Li("Milk")) .Build();page = html do h1 "Shopping list" ul do li "Eggs" li "Milk" endendNo return this, no lambda parameter to thread through, no Build() to forget. See
Type-safe builders to write your own.
Exceptions
Section titled “Exceptions”The same .NET exceptions, with Ruby’s keywords. rescue sounds more heroic than
catch anyway.
try{ Parse(path);}catch (FileNotFoundException e){ Log(e.Message);}finally{ Cleanup();}begin parse(path)rescue FileNotFoundException => e log e.messageensure cleanupendFor 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.
Pattern matching
Section titled “Pattern matching”case/when is an expression, and matching on a type narrows the value in that
branch.
var area = shape switch{ Circle c => Math.PI * c.Radius * c.Radius, Rectangle r => r.Width * r.Height, _ => 0.0,};area = case shape when Circle then Math::PI * shape.radius ** 2 when Rectangle then shape.width * shape.height else 0.0 endThe return type is written unwrapped; the compiler adds the Task. You may never type
Task<IReadOnlyDictionary<string, List<int>>> again. Not here, anyway.
public async Task<string> FetchAsync(string url){ var response = await http.GetAsync(url); return await response.Content.ReadAsStringAsync();}async def fetch(url: String): String response = await http.get_async(url) await response.content.read_as_string_asyncendCalling your C# code
Section titled “Calling your C# code”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.