Created
March 2, 2023 16:40
-
-
Save nklbdev/6b6503bdb46fd174ae72cd5b258c9af2 to your computer and use it in GitHub Desktop.
Option pattern C# implementation
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
| public interface IOption<T> : IEnumerable<T> | |
| { | |
| bool IsSome { get; } | |
| T Value { get; } | |
| IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); | |
| } | |
| public static class Option | |
| { | |
| public static IOption<T> Some<T>(T value) => new Some<T>(value); | |
| public static IOption<T> None<T>() => new None<T>(); | |
| } | |
| public readonly record struct Some<T>(T Value) : IOption<T> | |
| { | |
| public bool IsSome => true; | |
| public IEnumerator<T> GetEnumerator() => Enumerable.Repeat(Value, 1).GetEnumerator(); | |
| } | |
| public readonly record struct None<T>() : IOption<T> | |
| { | |
| public bool IsSome => false; | |
| public T Value => throw new InvalidOperationException(); | |
| public IEnumerator<T> GetEnumerator() => Enumerable.Empty<T>().GetEnumerator(); | |
| } | |
| public class A | |
| { | |
| public static IOption<int> GiveMeSome() => new Some<int>(10); | |
| public static void Method() | |
| { | |
| var q = GiveMeSome(); | |
| q.SingleOrDefault(10); | |
| foreach(var number in q) | |
| { | |
| // | |
| } | |
| var dd = q.Value; | |
| var e = Option.Some(10); | |
| var r = Option.None<int>(); | |
| int d = GiveMeSome() switch | |
| { | |
| Some<int> some => some.Value, | |
| _ => throw new NotImplementedException(), | |
| }; | |
| var ddd = d + 2; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment