Created
January 25, 2016 17:24
-
-
Save NickStrupat/289a33d4b1afc8ec1f66 to your computer and use it in GitHub Desktop.
A class which allow switch...case-style code for matching 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
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