Skip to content

Instantly share code, notes, and snippets.

@garata
Created July 23, 2014 13:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save garata/5f9806b93b5294ced34c to your computer and use it in GitHub Desktop.
Save garata/5f9806b93b5294ced34c to your computer and use it in GitHub Desktop.
C# Dispatch table based on "Generic Dictionary", "Collection Initializer" and "Lambda Expressions"
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();
}
}
@garata
Copy link
Author

garata commented Jul 23, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment