Skip to content

Instantly share code, notes, and snippets.

@alexbihary
Created September 2, 2013 02:31
Show Gist options
  • Save alexbihary/6408759 to your computer and use it in GitHub Desktop.
Save alexbihary/6408759 to your computer and use it in GitHub Desktop.
public static void TestTypeSwitch()
{
var ts = new TypeSwitch()
.Case((int x) => Console.WriteLine("int"))
.Case((bool x) => Console.WriteLine("bool"))
.Case((string x) => Console.WriteLine("string"));
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
}
public class TypeSwitch
{
Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; }
public void Switch(object x) { matches[x.GetType()](x); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment