Last active
October 23, 2024 15:00
-
-
Save ryanhossain9797/865d42fc2732bf40b8cda0e7417524f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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