Skip to content

Instantly share code, notes, and snippets.

@ufcpp
Created February 20, 2019 09:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ufcpp/13353d183f6af088cbf8a2380a58058b to your computer and use it in GitHub Desktop.
Save ufcpp/13353d183f6af088cbf8a2380a58058b to your computer and use it in GitHub Desktop.
Curried delegates
using System;
class Program
{
// M wants to get an instance via Func
static void M(Func<string> factory)
{
Console.WriteLine(factory());
}
static void Main()
{
// Caller wants to pass just a single instance to M
string s = Console.ReadLine();
// By using a lambda () => s
// this cause a heap allocation for an anonymous class
M(() => s);
// On the other hand, by using curried delegate
// no anonymous class
M(s.Identity);
}
}
static class TrickyExtension
{
// Returns the parameter as-is
public static T Identity<T>(this T x) => x;
}
using System;
static class Program
{
// A normal static method
static int F(int x) => 2 * x;
// Changes F to an extension with dummy object parameter
static int F(this object dummy, int x) => 2 * x;
static void Main()
{
// Creates a delegate from a normal static method
Func<int, int> s = F;
// Creates a curreid delegate with dummy null
Func<int, int> e = default(object).F;
// e (curried delegate) is much faster than s (normal static method)
s(10);
e(10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment