Skip to content

Instantly share code, notes, and snippets.

@mirmostafa
Created July 21, 2022 08:57
Show Gist options
  • Save mirmostafa/132eaea9fc306022dc9d374ac5ecfcf4 to your computer and use it in GitHub Desktop.
Save mirmostafa/132eaea9fc306022dc9d374ac5ecfcf4 to your computer and use it in GitHub Desktop.
Simple Monad Design Pattern in C#
public class Monad<TValue>
{
private readonly TValue? _value;
public Monad(TValue? value)
=> this._value = value;
public Monad<TResult?> AnyWay<TResult>(in Func<TValue?, TResult?> func)
=> new(func(this._value));
public Monad<TValue?> AnyWay(in Action<TValue?> func)
{
func(this._value);
return this;
}
public Monad<TResult?> NotNull<TResult>(in Func<TValue, TResult?> func)
=> this._value is not null ? new(func(this._value)) : new(default);
public Monad<TValue?> NotNull(in Action<TValue> func)
{
if (this._value is not null)
{
func(this._value);
}
return this;
}
}
var p = new Person("Ali", 5);
var maybe = new Monad<Person>(p)
.NotNull(p => new Person("Reza", 5))
.AnyWay(p => WriteLine($"p: {p}"))
.NotNull(_ => (Person?)null)
.AnyWay(p => WriteLine($"p: {p}"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment