Created
September 2, 2013 02:31
-
-
Save alexbihary/6408759 to your computer and use it in GitHub Desktop.
Type Switch
From http://stackoverflow.com/questions/7252186/switch-case-on-type-c-sharp/7301514#7301514
This file contains hidden or 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 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"); | |
} |
This file contains hidden or 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 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