Created
January 24, 2020 16:05
-
-
Save IanWold/2edfa92f8d19f1af092e7632629297d7 to your computer and use it in GitHub Desktop.
I get ticked about not having inline switch in c#
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 static class SwitchExtensions | |
{ | |
public static TReturn Switch<TInput, TReturn>(this TInput input, params (Predicate<TInput> check, Func<TInput, TReturn> value)[] cases) => | |
Switch(input, c => default, cases); | |
public static TReturn Switch<TInput, TReturn>(this TInput input, Func<TInput, TReturn> defaultCase, params (Predicate<TInput> check, Func<TInput, TReturn> value)[] cases) => | |
cases | |
.Concat(new (Predicate<TInput> check, Func<TInput, TReturn> value)[] { (c => true, defaultCase) }) | |
.First(c => c.check(input)) | |
.value(input); | |
} | |
public static class Example | |
{ | |
public static string GetTens(int toCheck) => toCheck.Switch( | |
defaultCase: i => "Something bigger than 100!", | |
(i => i >= 0 && i < 10, i => "Zeroes"), | |
(i => i > 10 && i < 20, i => "Tens"), | |
(i => i > 20 && i < 30, i => "Twenties"), | |
(i => i > 30 && i < 40, i => "Thirties"), | |
(i => i > 40 && i < 50, i => "Forites"), | |
(i => i > 50 && i < 60, i => "Fifties"), | |
(i => i > 60 && i < 70, i => "Sixties"), | |
(i => i > 70 && i < 80, i => "Seventies"), | |
(i => i > 80 && i < 90, i => "Eighties"), | |
(i => i > 90 && i < 100, i => "Nineties") | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment