Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Last active November 15, 2018 08:21
Show Gist options
  • Save JKamsker/509097c393294c2fa0d812c9c2e997a0 to your computer and use it in GitHub Desktop.
Save JKamsker/509097c393294c2fa0d812c9c2e997a0 to your computer and use it in GitHub Desktop.
Fluent typeswitch
using System;
using System.Collections.Generic;
using System.Linq;
namespace FluentHandler
{
internal class CustomHandler
{
private readonly List<ICheckable> _ceckables;
public CustomHandler()
{
_ceckables = new List<ICheckable>();
}
public void Handle<T>(T @object)
{
foreach (var checkable in _ceckables.Where(x => x.Check(@object)).Cast<IInvokable<T>>())
{
if (checkable.Invoke(@object))
{
return;
}
}
}
public void Handle(object @object)
{
foreach (var checkable in _ceckables.Where(x => x.Check(@object)).Cast<IInvokable>())
{
if (checkable.Invoke(@object))
{
return;
}
}
}
public ICanDoSomething<T> On<T>()
{
return On<T>(x => true);
}
public ICanDoSomething<T> On<T>(Predicate<T> condition)
{
var doSomething = new CanDoSomething<T>(condition);
_ceckables.Add(doSomething);
return doSomething;
}
}
internal class CanDoSomething<T> : ICanDoSomething<T>, IInvokable<T>, IInvokable, ICheckable
{
private readonly Predicate<T> _condition;
private Action<T> _action;
public CanDoSomething() : this(x => true)
{
}
public CanDoSomething(Predicate<T> condition)
{
_condition = condition;
}
public void Do(Action<T> action)
{
_action = action;
}
public bool Invoke(T value)
{
if (_action == null)
{
return false;
}
_action.Invoke(value);
return true;
}
public bool Check(object value)
{
return value is T typedValue && _condition(typedValue);
}
public bool Invoke(object value)
{
if (_action == null)
{
return false;
}
if (value is T invokeValue)
{
_action.Invoke(invokeValue);
return true;
}
return false;
}
}
internal interface IInvokable<in T>
{
bool Invoke(T value);
}
internal interface IInvokable
{
bool Invoke(object value);
}
internal interface ICheckable
{
bool Check(object value);
}
internal interface ICanDoSomething<out T>
{
void Do(Action<T> action);
}
internal class MyAwesomeClass
{
public string AwesomeString { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
object awesome = new MyAwesomeClass { AwesomeString = "YOU ARE AWESOME!" };
object awesome1 = new MyAwesomeClass { AwesomeString = "YOU ARE MORE AWESOME!" };
var handler = new CustomHandler();
handler.On<MyAwesomeClass>(x => x.AwesomeString.ToLower().Contains("more")).Do(x => Console.WriteLine($"Hello world {x.AwesomeString}"));
handler.Handle(awesome);
handler.Handle(awesome1);
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment