Created
July 23, 2014 13:05
-
-
Save garata/5f9806b93b5294ced34c to your computer and use it in GitHub Desktop.
C# Dispatch table based on "Generic Dictionary", "Collection Initializer" and "Lambda Expressions"
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
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
public class Program | |
{ | |
static void Main() | |
{ | |
Func<int, bool> Default = (x => true); | |
var myNum = 29; | |
// A dispatch table is a data structure that associates an index (or key) value to an action. | |
// It's a rather elegant replacement for a switch-case statement . | |
var cases = new Dictionary<Func<int, bool>, Action> | |
{ | |
{ x => x < 3, () => Console.WriteLine(String.Format("{0} is smaller than or equal to 3", myNum)) }, | |
{ x => x < 30, () => Console.WriteLine(String.Format("{0} is smaller than or equal to 30", myNum)) }, | |
{ x => x < 300, () => Console.WriteLine(String.Format("{0} is smaller than or equal to 300", myNum)) }, | |
{ Default, () => Console.WriteLine("Default case") } | |
}; | |
cases.FirstOrDefault(kvp => kvp.Key(myNum)).Value(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsil.org/try/#5f9806b93b5294ced34c