Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a good reason why extension method classes can't be nested?
    primarykey
    data
    text
    <p>I've been using extension methods a lot recently to help make my code be more fluent, but I keep running into situations where I can't limit the exposure of the functionality I've created in the way I'd like.</p> <p>Say I have some code like this (completely made up example):</p> <pre><code>var liveSet = allitems.Where(x =&gt; x.Status == Status.Live).Select(x =&gt; x.Name); var deadSet = allitems.Where(x =&gt; x.Status == Status.Dead).Select(x =&gt; x.Name); var zombieSet = allitems.Where(x =&gt; x.Status == Status.Neither).Select(x =&gt; x.Name); </code></pre> <p>I'd like to make this more fluent, and stop repeating myself:</p> <pre><code>var liveSet = allitems.SelectNameWhere(x =&gt; x.Status == Status.Live); ... </code></pre> <p>But I consider this to be a helper method, not a true extension and so I would like to limit its usage in the same way as I can a private method:</p> <pre><code>//In the same class private static IEnumerable&lt;string&gt; SelectNameWhere( this IEnumerable&lt;Element&gt; items, Func&lt;Element, bool&gt; predicate) ... </code></pre> <p>Unfortunately I can't do this because the class that holds the extension method must be static. Okay, not the end of the world, I'll nest a private static class to hold the method... Of course I can't do that either, so I'm left either exposing this method to at least an internal level, or removing the nice, fluent, nature of my code:</p> <pre><code>var liveSet = SelectNameFrom(allItems, x =&gt; x.Status == Status.Live); ... </code></pre> <p>These limitations on where you can declare an extension method seem fairly arbitrary to me, but I assume they have good logical or technical reasons. If so, what are they? </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.
    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