Skip to content

Instantly share code, notes, and snippets.

@louthy
Last active May 30, 2024 13:30
Show Gist options
  • Save louthy/73eee73f677e593f8977b183fe6497c1 to your computer and use it in GitHub Desktop.
Save louthy/73eee73f677e593f8977b183fe6497c1 to your computer and use it in GitHub Desktop.
Delegates as structs in C#
var freeVar = 100;
Func<string, int> length = x => x.Length + freeVar;
var f = new Fun<string, int>(length);
var r = f.Invoke("Hello");
Console.WriteLine(r); // 105
public readonly unsafe struct Fun<A>
{
readonly object? self;
readonly IntPtr func;
public Fun(object? self, IntPtr func) =>
(this.self, this.func) = (self, func);
public Fun(Func<A> function)
: this(function.Target, function.Method.MethodHandle.GetFunctionPointer())
{ }
public A Invoke()
{
var f = (delegate*<object?, A>)func;
return f(self);
}
}
public readonly unsafe struct Fun<A, B>
{
readonly object? self;
readonly IntPtr func;
public Fun(object? self, IntPtr func) =>
(this.self, this.func) = (self, func);
public Fun(Func<A, B> function)
: this(function.Target, function.Method.MethodHandle.GetFunctionPointer())
{ }
public B Invoke(in A value)
{
var f = (delegate*<object?, A, B>)func;
return f(self, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment