Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You just need to express the specific types. For example:</p> <pre><code>Func&lt;Func&lt;int, int&gt;, Func&lt;int, int&gt;&gt; </code></pre> <p>represents a function which takes a (function converting an int to a second int) and returns a (function converting an int to a second int). Or to take two functions and return a third:</p> <pre><code>Func&lt;Func&lt;int, int&gt;, Func&lt;int, int&gt;, Func&lt;int, int&gt;&gt; </code></pre> <p>For example:</p> <pre><code>Func&lt;Func&lt;int, int&gt;, Func&lt;int, int&gt;&gt; applyTwice = (f =&gt; x =&gt; f(f(x)); </code></pre> <p>This can be returned generically by a method:</p> <pre><code>public static Func&lt;Func&lt;T,T&gt;, Func&lt;T,T&gt;&gt; ApplyTwice&lt;T&gt;() { return func =&gt; x =&gt; func(func(x)); } </code></pre> <p>If you want to sum two functions, you might do:</p> <pre><code>public static Func&lt;int, int&gt; Sum(Func&lt;int, int&gt; first, Func&lt;int, int&gt; second) { return x =&gt; first(x) + second(x); } </code></pre> <p>Now to apply it:</p> <pre><code>Func&lt;int, int&gt; doubler = x =&gt; x * 2; Func&lt;int, int&gt; squarer = x =&gt; x * x; Func&lt;int, int&gt; doublePlusSquare = Sum(doubler, squarer); Console.WriteLine(doublePlusSquare(5)); // Prints 35 </code></pre> <p>(Untested, but should be okay...)</p> <hr> <p>If you don't have C# 3 and .NET 3.5 available to you, then declare the following delegates:</p> <pre><code>public delegate TResult Func&lt;TResult&gt;(); public delegate TResult Func&lt;T, TResult&gt;(T arg); public delegate TResult Func&lt;T1, T2, TResult&gt;(T1 arg1, T2 arg2); </code></pre> <p>(There's more on my <a href="http://csharpindepth.com/Articles/Chapter1/Versions.aspx" rel="noreferrer">C# Versions page</a>.)</p> <p>Then you'll need to use anonymous methods, e.g.</p> <pre><code>public static Func&lt;int, int&gt; Sum(Func&lt;int, int&gt; first, Func&lt;int, int&gt; second) { return delegate(int x) { return first(x) + second(x); }; } Func&lt;int, int&gt; doubler = delegate (int x) { return x * 2; }; Func&lt;int, int&gt; squarer = delegate (int x) { return x * x; }; Func&lt;int, int&gt; doublePlusSquare = Sum(doubler, squarer); Console.WriteLine(doublePlusSquare(5)); // Prints 35 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload