Skip to content

Instantly share code, notes, and snippets.

@nitinjs
Last active March 31, 2023 18:25
Show Gist options
  • Save nitinjs/10ce0ee2e377c88c8a9bde1ab9440336 to your computer and use it in GitHub Desktop.
Save nitinjs/10ce0ee2e377c88c8a9bde1ab9440336 to your computer and use it in GitHub Desktop.
golang defer keyword alternative in C#
//Author: Nitin Sawant
//add reference to AspectInjector package https://github.com/pamidur/aspect-injector
using AspectInjector.Broker;
using System.Reflection;
DeferTest test = new DeferTest();
test.Test();
public class DeferTest
{
[Deferrable]
public void Test()
{
int i = 0;
Defer.Me(() => { Console.WriteLine("1"); });
Defer.Me(() => { Console.WriteLine("2"); });
i++;
Defer.Me(() => { Console.WriteLine("3"); });
Defer.Me(() => { Console.WriteLine("4"); });
if (i > 0)
return;
Defer.Me(() => { Console.WriteLine("5"); });
}
}
#region DeferLib
[Aspect(Scope.Global)]
[Injection(typeof(DeferrableAttribute))]
public class DeferrableAttribute : Attribute
{
[Advice(Kind.After)]
public void Executed([Argument(Source.Name)] string name)
{
Defer.Execute();
}
}
public class Defer
{
private static Stack<Action> Actions { get; set; }
static Defer() { Actions = new Stack<Action>(); }
public static void Me(Action a)
{
Actions.Push(a);
}
public static void Execute(Action action)
{
action();
Execute();
}
public static void Execute()
{
while (Actions.Count > 0)
{
var a = Actions.Pop();
a();
}
}
}
#endregion
@nitinjs
Copy link
Author

nitinjs commented Mar 31, 2023

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment