Last active
September 24, 2019 17:50
-
-
Save lawrencegripper/afc8ac5de11f4c90cbab96fdafe7b899 to your computer and use it in GitHub Desktop.
C# 8 `defer` like golang
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
using System; | |
namespace deferdotnet | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
try | |
{ | |
DoStuff(); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine($"Exception thrown: {e.Message}"); | |
} | |
} | |
private static void DoStuff() | |
{ | |
using var d = new Defer(() => Console.WriteLine("Defer 1")); | |
using var f = new Defer(() => Console.WriteLine("Defer 2")); | |
Console.WriteLine("Hello World!"); | |
throw new Exception("It's all one wrong"); | |
} | |
} | |
// Do the `defer` magic | |
public class Defer : IDisposable | |
{ | |
private Action deferFunc { get; } | |
public Defer(Action deferFunc) | |
{ | |
this.deferFunc = deferFunc; | |
} | |
public void Dispose() | |
{ | |
deferFunc(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment