Created
February 20, 2019 09:42
-
-
Save ufcpp/13353d183f6af088cbf8a2380a58058b to your computer and use it in GitHub Desktop.
Curried delegates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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