Note that there are some explanatory texts on larger screens.

plurals
  1. POC# syntax for applying an action to a varying number of objects
    primarykey
    data
    text
    <p>What I want to do is combine lambda syntax with "params" to carry out an action on a series of object.</p> <p>Let's say I want to make a bunch of controls invisible.</p> <p>After a bit of fiddling I ended up with an extension method:</p> <pre><code>public static void On&lt;T&gt;(this Action&lt;T&gt; actionToCarryOut,params T[] listOfThings) { foreach (var thing in listOfThings) { actionToCarryOut(thing); } } </code></pre> <p>and then I can create an action:</p> <pre><code>Action&lt;Control&gt; makeInvisible = c =&gt; c.Visible = false; </code></pre> <p>and then call it:</p> <pre><code>makeInvisible.On(control1,control2, control3,control4); </code></pre> <p>This isn't very nice syntax though - it feels horribly clumsy.</p> <p>I can create a method "Apply" in my base class:</p> <pre><code>protected void Apply&lt;T&gt;(Action&lt;T&gt; action, params T[] appliedTo) { foreach (var item in appliedTo) { action(item); } } </code></pre> <p>and then call it like this:</p> <pre><code>Apply&lt;Control&gt;( c =&gt; c.Visible = false, control1, control2, control3,); </code></pre> <p>But that means repeating the method in every base class I need it in, and I lose the advantage of type inference.</p> <p>Is there a less clumsy way of doing this?</p> <p>Edit: The nicest method I've seen so far is the fluent approach, which (with a couple of tweaks) would allow me to write:</p> <pre><code>Apply.Method((Control c) =&gt; c.Visible = false).To( control1, control2, control3, control4}; </code></pre> <p>This is 91 characters, compared to 107 for using a simple "foreach". Which leads me to believe that "foreach" might actually be the best approach after all!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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