A maybe monad for C#.
A maybe monad is a good way to avoid nulls. So you avoid returning null by doing:
publicMaybe<string>Foo(){if(checkThis()){return"A string".ToMaybe();}returnMaybe<string>.Nothing;}Because Maybe<T> is a struct this means it cannot have a null value. So instead of checking for null you'll have to verify if the returned object has a value before consuming it.
There are multiple ways to retrieve the value of a Maybe<T>.
varmaybe="some value".ToMaybe();// this will throw if it has no valuevarv=maybe.Value;v=maybe.Or("");v=maybe.Or(()=>FindAValue());v=maybe.OrThrow(()=>newArgumentException());// when T is a classv=maybe.OrNull();// when T is a stringv=maybe.OrEmpty();// returns a Maybe<int>varlength=maybe.Select(s =>s.Length);// returns a string?vars=maybe.ToNullable();There are other ways of using it in a more fluent-like API.
varmaybe="some value".ToMaybe();// CallMethod is only called if maybe has a valuemaybe.Consume(s =>CallMethod(s));// returns a Maybe<string>varresult=maybe.Where(s =>s.StartsWith("some"));Comparing maybes is also supported.
vara=10.ToMaybe();varb=0.ToMaybe();if(a>b){// do stuff}a=Maybe<int>.Nothing;b=int.MinValue;if(a<b){// Nothing will always be less than any int value}It is also possible to implicitly cast any object of type T to a Maybe<T>. For example, the following snippets are valid:
Maybe<int>a=10;publicMaybe<double>Foo(){return1.0;}