Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to define parameter names for higher order functions in C#
    text
    copied!<p>In C# it is possible to create higher order functions, ie. functions <code>g</code> taking functions as arguments. Say I want to create such a function which given a function <code>f</code> and returns another function extending its functionality. <b>How do I define argument names for the returned enhanced method?</b> The motivation being, that I'm working with higher order methods in general, some of which produce new methods.. and these can be difficult to use as there is no parameter names etc. attached to them.</p> <p>An example illustrating how <code>g</code> and <code>f</code> respectively could be defined in C#:</p> <p>I define a method Extend that can extens methods taking a <code>T</code> as argument and returning an <code>S</code>. <code><pre> static class M { public static Func&lt; T, S> Extend(Func&lt; T, S> functionToWrap) { return (someT) => { ... var result = functionToWrap(someT); ... return result; }; } } </pre></code></p> <p>We can then extend a method on our class without changing the method. <code><pre> class Calc2 { public Func&lt; int, int> Calc; public Calc2() { Calc = M.Extend&lt; int, int>(CalcPriv); } private int CalcPriv(int positiveNumber) { if(positiveNumber &lt; 0) throw new Exception(...); Console.WriteLine("calc " + i); return i++; } } </pre></code></p> <p>Alas, the argument name <code>positiveNumber</code> is no longer available, since the only available information is <code>Func&lt;int, int&gt; Calc</code>. That is when I use the extended method by typing <code>new Calc2().Calc(-1)</code> I get no help from the IDE that in fact my argument is wrong.</p> <p>It would be nice if we could define a <code>delegate</code> and cast it to this, however, this is not possible. </p> <p>Any suggestions?</p>
 

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