Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maybe/Option monad in C# [closed]

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?

like image 229
Felix Avatar asked Mar 18 '15 15:03

Felix


People also ask

Is maybe a Monad?

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.

How to use Maybe in c#?

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.

What is a Monad C#?

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.


1 Answers

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);
like image 143
JLRishe Avatar answered Oct 14 '22 10:10

JLRishe