Skip to content

Instantly share code, notes, and snippets.

@arxae
Last active December 26, 2015 14:49
Show Gist options
  • Save arxae/7168871 to your computer and use it in GitHub Desktop.
Save arxae/7168871 to your computer and use it in GitHub Desktop.
Dispatch tables
// Regular dispatch table
Dictionary<string, Action> dispatch = new Dictionary<string, Action>();
dispatch["help"] = new Action(() => Console.WriteLine("Hello :3"));
dispatch["dosomething"] = new Action(() =>
{
Console.WriteLine("Do Something else");
});
dispatch["help"]();
// Using delegates
Dictionary<string, Delegate> dispatch = new Dictionary<string, Delegate>();
dispatch["help"] = new Action(() => Console.WriteLine("Hello"));
dispatch["dosomething"] = new Action<string>(s => Console.WriteLine(s));
dispatch["help"].DynamicInvoke();
dispatch["dosomething"].DynamicInvoke("World!");
// Using dynamic (starting from .NET 4)
Dictionary<string, dynamic> dispatch = new Dictionary<string, dynamic>();
dispatch["help"] = new Action(() => Console.WriteLine("Hello"));
dispatch["dosomething"] = new Action<string>(s => Console.WriteLine(s));
dispatch["help"]();
dispatch["dosomething"]("World");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment