Last active
December 12, 2015 01:18
-
-
Save phatty/4689880 to your computer and use it in GitHub Desktop.
c# implement switch with Type
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
TypeSwitch.Do( | |
sender, | |
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"), | |
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked), | |
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over")); | |
static class TypeSwitch { | |
public class CaseInfo { | |
public bool IsDefault { get; set; } | |
public Type Target { get; set; } | |
public Action<object> Action { get; set; } | |
} | |
public static void Do(object source, params CaseInfo[] cases) { | |
var type = source.GetType(); | |
foreach (var entry in cases) { | |
if (entry.IsDefault || entry.Target.IsAssignableFrom(type)) { | |
entry.Action(source); | |
break; | |
} | |
} | |
} | |
public static CaseInfo Case<T>(Action action) { | |
return new CaseInfo() { | |
Action = x => action(), | |
Target = typeof(T) | |
}; | |
} | |
public static CaseInfo Case<T>(Action<T> action) { | |
return new CaseInfo() { | |
Action = (x) => action((T)x), | |
Target = typeof(T) | |
}; | |
} | |
public static CaseInfo Default(Action action) { | |
return new CaseInfo() { | |
Action = x => action(), | |
IsDefault = true | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment