Skip to content

Instantly share code, notes, and snippets.

@ryanhossain9797
Last active October 23, 2024 15:00
Show Gist options
  • Select an option

  • Save ryanhossain9797/865d42fc2732bf40b8cda0e7417524f8 to your computer and use it in GitHub Desktop.

Select an option

Save ryanhossain9797/865d42fc2732bf40b8cda0e7417524f8 to your computer and use it in GitHub Desktop.
using System;
public abstract class Option<T>
{
public static Option<T> some(T value) => new Some(value); //we need these to make the actual Some/None constructors internal
public static Option<T> none() => new None();
public sealed class Some : Option<T>
{
public readonly T value;
internal Some(T value) //internal so nobody can create a standalone Some or None instance
{
this.value = value ?? throw new ArgumentNullException(nameof(value));
}
}
public sealed class None : Option<T>
{
internal None() { }
}
}
public class HelloWorld
{
public static void Main(string[] args)
{
Option<int> someValue = Option<int>.some(42);
Option<int> noneValue = Option<int>.none();
var valueOrDefault =
someValue switch {
Option<int>.Some { value: var num } => num,
_ => 0
//Option<int>.None => 0, //You could also match none but it's not exhaustive so you'd need _ anyway
};
Console.WriteLine(valueOrDefault); //prints 42
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment