Skip to content

Instantly share code, notes, and snippets.

@seralexeev
Created November 29, 2016 12:47
Show Gist options
  • Save seralexeev/be1165ae1747f90f2dd29f9a32feb55e to your computer and use it in GitHub Desktop.
Save seralexeev/be1165ae1747f90f2dd29f9a32feb55e to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
class Program {
public static void Main() {
var input = "12";
using (new switchOf(input) {
(int a) => Console.WriteLine($"int: {a}"),
(string a) => Console.WriteLine($"string: {a}"),
});
}
}
class switchOf : IEnumerable, IDisposable {
Dictionary<Type, Action<object>> _handlers = new Dictionary<Type, Action<object>>();
object _obj;
public switchOf(object obj) {
_obj = obj;
}
public void Add<T> (Action<T> action) {
var type = typeof(T);
if(_handlers.ContainsKey(type))
throw new InvalidOperationException();
_handlers[type] = (object o) => action((T) o);
}
public void Dispose() {
var type = _obj.GetType();
if (_handlers.TryGetValue(type, out var handler)) {
handler(_obj);
}
}
IEnumerator IEnumerable.GetEnumerator() => null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment