Skip to content

Instantly share code, notes, and snippets.



Last active Sep 8, 2019
What would you like to do?
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);
return seed;

This comment has been minimized.

Copy link
Owner Author

@ploeh ploeh commented Jan 23, 2018

Usage example:

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

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
You can’t perform that action at this time.