Created
November 8, 2015 08:01
-
-
Save AndriiTsok/38e3747735d6bd46d8b4 to your computer and use it in GitHub Desktop.
Switch by type
This file contains 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
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
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"));