Last active
November 4, 2020 03:12
-
-
Save michael-wolfenden/a9cf21da919395725cca78650dcd2bcd to your computer and use it in GitHub Desktop.
Pattern
This file contains 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 class Pattern<TReturn> | |
: List<(Type Type, Func<object, TReturn> Map)> | |
{ | |
public void Add<T>(Func<T, TReturn> map) | |
=> Add((typeof(T), o => map((T)o))); | |
public Pattern<TReturn> Default(TReturn val) | |
{ | |
Add((object _) => val); | |
return this; | |
} | |
public TReturn Match(object value) | |
{ | |
var map = this.FirstOrDefault(x => x.Type.IsInstanceOfType(value)).Map; | |
if (map == null) | |
throw new NotImplementedException($"No map found for type '{value.GetType()}"); | |
return map(value); | |
} | |
} | |
// Example | |
var pattern = new Pattern<string> | |
{ | |
(ArgumentNullException e) => $"Paramter '{e.ParamName}' was null", | |
(DivideByZeroException _) => "Can't divide by zero", | |
} | |
.Default("Oops something went wrong"); | |
// returns: Paramter 'some parameter' was null | |
pattern.Match(new ArgumentNullException("some parameter")); | |
// returns: Can't divide by zero | |
pattern.Match(new DivideByZeroException()); | |
// returns: Oops something went wrong | |
pattern.Match(new Exception()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment