Created
February 1, 2013 07:33
-
-
Save phatty/4689928 to your computer and use it in GitHub Desktop.
c# Type Switch More
This file contains hidden or 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
new Switch(foo) | |
.Case<Fizz> | |
(action => { doingSomething = FirstMethodCall(); }) | |
.Case<Buzz> | |
(action => { return false; }) | |
public class Switch | |
{ | |
public Switch(Object o) | |
{ | |
Object = o; | |
} | |
public Object Object { get; private set; } | |
} | |
/// <summary> | |
/// Extensions, because otherwise casing fails on Switch==null | |
/// </summary> | |
public static class SwitchExtensions | |
{ | |
public static Switch Case<T>(this Switch s, Action<T> a) | |
where T : class | |
{ | |
return Case(s, o => true, a, false); | |
} | |
public static Switch Case<T>(this Switch s, Action<T> a, | |
bool fallThrough) where T : class | |
{ | |
return Case(s, o => true, a, fallThrough); | |
} | |
public static Switch Case<T>(this Switch s, | |
Func<T, bool> c, Action<T> a) where T : class | |
{ | |
return Case(s, c, a, false); | |
} | |
public static Switch Case<T>(this Switch s, | |
Func<T, bool> c, Action<T> a, bool fallThrough) where T : class | |
{ | |
if (s == null) | |
{ | |
return null; | |
} | |
T t = s.Object as T; | |
if (t != null) | |
{ | |
if (c(t)) | |
{ | |
a(t); | |
return fallThrough ? s : null; | |
} | |
} | |
return s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment