Last active
March 15, 2018 20:51
-
-
Save bronumski/eaae7dca12aa7558d7d4f5bde14f3039 to your computer and use it in GitHub Desktop.
C# Functional Try Catch Finally
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 static int Main(string[] args) => | |
Try | |
.Action(() => 0) | |
.WithCatch<Exception>(ex => 1}) | |
.Finally(CleanUpMethod); |
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
static class Try | |
{ | |
public static Try<TResult> Action<TResult>(Func<TResult> act) | |
{ | |
return new Try<TResult>(act); | |
} | |
} | |
class Try<TResult> | |
{ | |
Func<TResult> action; | |
List<Func<Exception, TResult>> catchActions = new List<Func<Exception, TResult>>(); | |
private Try(Func<TResult> action) | |
{ | |
this.action = action; | |
} | |
public static Try<TResult> Action<TResult>(Func<TResult> act) | |
{ | |
return new Try<TResult>(act); | |
} | |
public Try<TResult> WithCatch<TException>(Func<TException, TResult> act) where TException : Exception | |
{ | |
catchActions.Add((Func<Exception, TResult>)act); | |
return this; | |
} | |
public TResult Finally(Action act) | |
{ | |
try | |
{ | |
return action(); | |
} | |
catch(Exception ex) | |
{ | |
foreach(var catchAction in catchActions) | |
{ | |
return catchAction(ex); | |
} | |
throw ex; | |
} | |
finally | |
{ | |
act(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment