Last active
January 4, 2023 15:44
-
-
Save savaged/261feac14103a49360191ad0f10e112b to your computer and use it in GitHub Desktop.
Monad pattern example for explicit null handling
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
| namespace MonadFun; | |
| // | |
| // Inspired by Mikhail Shilkov's blog https://mikhail.io/2016/01/monads-explained-in-csharp/ | |
| // | |
| public class Maybe<T> : IEquatable<Maybe<T>> | |
| where T : class? | |
| { | |
| private readonly T? _value; | |
| private Maybe() {} | |
| public Maybe(T? value) | |
| { | |
| _value = value; | |
| } | |
| public Maybe<TO> Bind<TO>(Func<T, Maybe<TO>> f) where TO : class? => | |
| _value != null ? f(_value) : Maybe<TO>.None(); | |
| public bool IsNone => _value == null; | |
| public IEnumerable<T> AsEnumerable() | |
| { | |
| if (_value != null) yield return _value; | |
| } | |
| public static Maybe<T> None() => new(); | |
| public static implicit operator T?(Maybe<T> m) => | |
| m?.IsNone == false ? m.AsEnumerable().FirstOrDefault() : default; | |
| public T GetValue(Func<T> defaultIfNull) => | |
| (IsNone == false ? _value : defaultIfNull()) ?? throw new InvalidOperationException( | |
| "Gave you a chance to prevent a null reference and you have failed miserably!"); | |
| public bool Equals(Maybe<T>? other) | |
| { | |
| if (ReferenceEquals(null, other)) return false; | |
| return ReferenceEquals(this, other) || EqualityComparer<T?>.Default.Equals(_value, other._value); | |
| } | |
| public override bool Equals(object? obj) | |
| { | |
| if (ReferenceEquals(null, obj)) return false; | |
| if (ReferenceEquals(this, obj)) return true; | |
| return obj.GetType() == GetType() && Equals((Maybe<T>)obj); | |
| } | |
| public override int GetHashCode() => | |
| _value != null ? EqualityComparer<T?>.Default.GetHashCode(_value) : 0; | |
| public static bool operator ==(Maybe<T>? left, Maybe<T>? right) | |
| { | |
| return Equals(left, right); | |
| } | |
| public static bool operator !=(Maybe<T>? left, Maybe<T>? right) | |
| { | |
| return !Equals(left, right); | |
| } | |
| } | |
| public static class MaybeEx | |
| { | |
| public static Maybe<T> Return<T>(this Maybe<T> @this) where T : class => | |
| @this?.IsNone == false ? new Maybe<T>(@this.AsEnumerable().FirstOrDefault()) : Maybe<T>.None(); | |
| } |
savaged
commented
Jan 4, 2023
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment