Skip to content

Instantly share code, notes, and snippets.

@battermann
Last active November 1, 2016 21:56
Show Gist options
  • Save battermann/ff6c11a9e3f6835010e21c1ac67fe96b to your computer and use it in GitHub Desktop.
Save battermann/ff6c11a9e3f6835010e21c1ac67fe96b to your computer and use it in GitHub Desktop.
CondictionalsExtensions
public static class CondictionalsExtensions
{
public static Tuple<bool, T> If<T>(this T src, Predicate<T> p)
{
return p(src)
? Tuple.Create(true, src)
: Tuple.Create(false, src);
}
public static Tuple<bool, T, R> Then<T, R>(this Tuple<bool, T> src, Func<T, R> f)
{
return src.Item1
? Tuple.Create(src.Item1, src.Item2, f(src.Item2))
: Tuple.Create(src.Item1, src.Item2, default(R));
}
public static R Else<T,R>(this Tuple<bool, T, R> src, Func<T,R> f)
{
return src.Item1
? src.Item3
: f(src.Item2);
}
}
[TestFixture]
class ConditionalsExtensionsTests
{
[Test]
public void Test()
{
var result = new[] { 1, 2, 3, 4 }
.If(x => x.Any())
.Then(x => $"List contains {x.Count()} elements")
.Else(_ => "List is empty");
Check.That(result).IsEqualTo("List contains 4 elements");
var result2 = new List<int>()
.If(x => x.Any())
.Then(x => $"List contains {x.Count()} elements")
.Else(_ => "List is empty");
Check.That(result2).IsEqualTo("List is empty");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment