Last active
March 2, 2016 16:30
-
-
Save hudo/d131a5ad057fddcb4e2c to your computer and use it in GitHub Desktop.
Pattern Matching 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
| public static class Match | |
| { | |
| public static PatternMatch<T, R> With<T, R>(T value) | |
| { | |
| return new PatternMatch<T, R>(value); | |
| } | |
| public struct PatternMatch<T, R> | |
| { | |
| private readonly T _value; | |
| private R _result; | |
| private bool _matched; | |
| public PatternMatch(T value) | |
| { | |
| _value = value; | |
| _matched = false; | |
| _result = default(R); | |
| } | |
| public PatternMatch<T, R> When(Func<T, bool> condition, Func<R> action) | |
| { | |
| if (!_matched && condition(_value)) | |
| { | |
| _result = action(); | |
| _matched = true; | |
| } | |
| return this; | |
| } | |
| public PatternMatch<T, R> When<C>(Func<C, R> action) | |
| { | |
| if (!_matched && _value is C) | |
| { | |
| _result = action((C)(object)_value); | |
| _matched = true; | |
| } | |
| return this; | |
| } | |
| public PatternMatch<T, R> When<C>(C value, Func<R> action) | |
| { | |
| if (!_matched && value.Equals(_value)) | |
| { | |
| _result = action(); | |
| _matched = true; | |
| } | |
| return this; | |
| } | |
| public R Result => _result; | |
| public R Default(Func<R> action) | |
| { | |
| return !_matched ? action() : _result; | |
| } | |
| } | |
| } | |
| // examples: | |
| var result = Match.With<IFoo, int>(new Foo() { A = 5 }) | |
| .When<IFoo>(foo => foo.A) | |
| .When<IBar>(bar => bar.B) | |
| .When<string>(Convert.ToInt32) | |
| .Result; | |
| Assert.Equal(5, result); | |
| var result = Match.With<int, string>(n) | |
| .When(x => x > 100, () => "n>100") | |
| .When(x => x > 10, () => "n>10") | |
| .Default(() => ""); | |
| Assert.Equal("n>10", result); | |
| var result = Match.With<int, string>(5) | |
| .When(1, () => "1") | |
| .When(5, () => "5") | |
| .Default(() => "e"); | |
| Assert.Equal("5", result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage?