Last active
September 8, 2019 19:54
-
-
Save ploeh/9e7d1594cd93807c05fa7d8a79667f13 to your computer and use it in GitHub Desktop.
Skeleton Maybe in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example:
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 ofAggregate
.