Skip to content

Instantly share code, notes, and snippets.

@lawrencegripper
Last active September 24, 2019 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lawrencegripper/afc8ac5de11f4c90cbab96fdafe7b899 to your computer and use it in GitHub Desktop.
Save lawrencegripper/afc8ac5de11f4c90cbab96fdafe7b899 to your computer and use it in GitHub Desktop.
C# 8 `defer` like golang
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