It's 2015, is there any "official" maybe monad in C#? Ideally, it would work something ala Scala's Option, Some and None types.
C# seems to have everything needed, i.e. co/contravariance and lambdas.
I'm asking this because I recently started working in a company that uses Unity, and I run into a lot of delayed initialization. In an attempt to avoid NullPointerException, I would like to maybe invite them into the monad world. Any ideas on this, or should we simply deal with this in another way?
Using Maybe is a good way to deal with errors or exceptional cases without resorting to drastic measures such as error . The Maybe type is also a monad. It is a simple kind of error monad, where all errors are represented by Nothing . A richer error monad can be built using the Either type.
This means that if we construct Maybe<string> like this: var maybe = new Maybe< string >(); ..the value field will get the value of null (the default for string), and the hasValue field will get the value of false (the default of bool). This will indicate that this instance contains no value.
In C# terms, a Monad is a generic class with two operations: constructor and bind. class Monad<T> { Monad(T instance); Monad<U> Bind(Func<T, Monad<U>> f); } Constructor is used to put an object into container, Bind is used to replace one contained object with another contained object.
As far as "official" approaches go, remember that if you're using C# 6, you can use the null-conditional operator:
var myVal = possiblyNull?.thisToo?.andThis?.value;
Certain VisualStudio templates (such as the ASP.NET MVC project template) also include the IsNotNull
extension method, which is part of the AjaxMinExtensions. If you don't have those in your project, you could copy/paste the implementation into your code.
var myVal = possiblyNull.IfNotNull(v => v.doTheThing())
.IfNotNull(theThing => theThing.TheProperty);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With