Monads in c#

An elegant example of functional mapping.
You need this framework at the very core of your app, where a light object relational map must be bundled to the model classes.
image

One day you’ll discover that a class in your build method is surprisingly null because a DateTime was fluent mapped to a null field.
Here is the smart extension that does the magic 🙂

public static class NullableExtension
{
public static Tout Maybe <Tin, Tout> (this Tin canBeNull, Func property)
	{
	if (canBeNull == null) {
		return default(Tout);
	}
	return property(canBeNull);
	}
}

And now enjoy its elegant usage!

DateTime JustADate = ANullableDateTime.Maybe(x => x.Value.Date);

Have you noticed the parametric types BTW?

Advertisements

One thought on “Monads in c#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s