Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In regards to <strong>why</strong> are closures mutable in C#, you have to ask, "Do you want simplicity (Java), or power with complexity (C#)?" </p> <p>Mutable closures allow you to define once and reuse. Example:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClosureTest { class Program { static void Main(string[] args) { string userFilter = "C"; IEnumerable&lt;string&gt; query = (from m in typeof(String).GetMethods() where m.Name.StartsWith(userFilter) select m.Name.ToString()).Distinct(); while(userFilter.ToLower() != "q") { DiplayStringMethods(query, userFilter); userFilter = GetNewFilter(); } } static void DiplayStringMethods(IEnumerable&lt;string&gt; methodNames, string userFilter) { Console.WriteLine("Here are all of the String methods starting with the letter \"{0}\":", userFilter); Console.WriteLine(); foreach (string methodName in methodNames) Console.WriteLine(" * {0}", methodName); } static string GetNewFilter() { Console.WriteLine(); Console.Write("Enter a new starting letter (type \"Q\" to quit): "); ConsoleKeyInfo cki = Console.ReadKey(); Console.WriteLine(); return cki.Key.ToString(); } } } </code></pre> <p>If you do not want to define once and reuse, because you are worried about unintended consequences, you can simply use a <em>copy of</em> the variable. Change the above code as follows:</p> <pre><code> string userFilter = "C"; string userFilter_copy = userFilter; IEnumerable&lt;string&gt; query = (from m in typeof(String).GetMethods() where m.Name.StartsWith(userFilter_copy) select m.Name.ToString()).Distinct(); </code></pre> <p>Now the query will return the same result, regardless of what <code>userFilter</code> equals.</p> <p>Jon Skeet has an excellent introduction to <a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx" rel="nofollow noreferrer">the differences between Java and C# closures</a>.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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