Skip to content

Instantly share code, notes, and snippets.

@adammyhre
Created December 22, 2024 08:44
Show Gist options
  • Save adammyhre/6878e7cb8df9a814cc9f83c1621867f8 to your computer and use it in GitHub Desktop.
Save adammyhre/6878e7cb8df9a814cc9f83c1621867f8 to your computer and use it in GitHub Desktop.
Simple Closure Implementation for Unity C#
using System;
public struct Closure<TContext> {
Delegate del;
TContext context;
public Closure(Delegate del, TContext context = default) {
this.del = del;
this.context = context;
}
public void Invoke() {
if (del is Action action) {
action();
} else if (del is Action<TContext> actionWithContext) {
actionWithContext(context);
} else {
throw new InvalidOperationException("Unsupported delegate type for Invoke.");
}
}
public TResult Invoke<TResult>() {
if (del is Func<TResult> func) {
return func();
} else if (del is Func<TContext, TResult> funcWithContext) {
return funcWithContext(context);
} else {
throw new InvalidOperationException("Unsupported delegate type for Invoke<TResult>.");
}
}
public static Closure<TContext> Create(Action action) => new Closure<TContext>(action);
public static Closure<TContext> Create(Action<TContext> action, TContext context) => new Closure<TContext>(action, context);
public static Closure<TContext> Create<TResult>(Func<TResult> func) => new Closure<TContext>(func);
public static Closure<TContext> Create<TResult>(Func<TContext, TResult> func, TContext context) => new Closure<TContext>(func, context);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment