Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created January 25, 2016 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/289a33d4b1afc8ec1f66 to your computer and use it in GitHub Desktop.
Save NickStrupat/289a33d4b1afc8ec1f66 to your computer and use it in GitHub Desktop.
A class which allow switch...case-style code for matching type
public class TypeSwitch : ReadOnlyTypeSwitch {
public TypeSwitch Case<T>(Action<T> action) {
matches.Add(typeof(T), x => action((T) x));
return this;
}
public ReadOnlyTypeSwitch Default(Action @default) {
this.@default = @default ?? delegate { };
return this;
}
}
public class ReadOnlyTypeSwitch {
protected Action @default = delegate { };
protected readonly Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
protected ReadOnlyTypeSwitch() { }
public void Switch<T>(T x) {
Action<object> a;
if (matches.TryGetValue(x.GetType(), out a))
a(x);
else
@default();
}
}
static void Main(string[] args) {
var ts = new TypeSwitch()
.Case<int>(x => Console.WriteLine("int"))
.Case<bool>(x => Console.WriteLine("bool"))
.Case<string>(x => Console.WriteLine("string"))
.Default(() => { throw new ArgumentOutOfRangeException(); });
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment