Skip to content

Instantly share code, notes, and snippets.

@AndriiTsok
Created November 8, 2015 08:01
Show Gist options
  • Save AndriiTsok/38e3747735d6bd46d8b4 to your computer and use it in GitHub Desktop.
Save AndriiTsok/38e3747735d6bd46d8b4 to your computer and use it in GitHub Desktop.
Switch by type
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
};
}
}
@AndriiTsok
Copy link
Author

TypeSwitch.Do(
sender,
TypeSwitch.Case(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));

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