Skip to content

Instantly share code, notes, and snippets.

@ploeh
Last active September 8, 2019 19:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ploeh/9e7d1594cd93807c05fa7d8a79667f13 to your computer and use it in GitHub Desktop.
Save ploeh/9e7d1594cd93807c05fa7d8a79667f13 to your computer and use it in GitHub Desktop.
Skeleton Maybe in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ploeh.Samples.ChainOfResponsibility
{
public class Maybe<T>
{
internal bool HasItem { get; }
internal T Item { get; }
public Maybe()
{
this.HasItem = false;
}
public Maybe(T item)
{
if (item == null)
throw new ArgumentNullException(nameof(item));
this.HasItem = true;
this.Item = item;
}
public TAccumulate Aggregate<TAccumulate>(
TAccumulate seed,
Func<TAccumulate, T, TAccumulate> func)
{
if (seed == null)
throw new ArgumentNullException(nameof(seed));
if (func == null)
throw new ArgumentNullException(nameof(func));
if (this.HasItem)
return func(seed, this.Item);
else
return seed;
}
}
}
@ploeh
Copy link
Author

ploeh commented Jan 23, 2018

Usage example:

> var m = new Maybe<string>("foo").Aggregate("", (_, s) => s);
> m
"foo"

You can only get the value out of the container unless you somehow deal with the case where it might be empty. It's possible to build all sorts of convenience functionality (e.g. DefaultIfEmpty) on top of Aggregate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment