According to the accepted answer to  enumerators in C# must be disposed when finished with, whether you let foreach do this automatically, or do it yourself if you prefer to write out the equivalent logic by hand. I wasn't expecting this; would have thought enumerators would be handled by the garbage collector. I'm guessing it's along the lines of:  Database queries are also enumerable, and those need to be disposed because they could be holding database connections, which are a scarcer resource than memory.  To correctly handle this case, the framework designers decided to just make enumerators implement IDisposable, so the contract is they should always be disposed; for in-memory collections like strings, arrays and lists, this will be a no-op, but it makes the overall design simpler than trying to make some kinds of enumerators implement a different interface.   Is this correct, or am I missing something?
57326
I noticed that the generic IEnumerator&lt;T&gt; inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way?  Usually, we use foreach statement to go through a IEnumerator&lt;T&gt; instance. The generated code of foreach actually has try-finally block that invokes Dispose() in finally.
81176
The following is okay: try {     Console.WriteLine(&quot;Before&quot;);      yield return 1;      Console.WriteLine(&quot;After&quot;); } finally {     Console.WriteLine(&quot;Done&quot;); }  The finally block runs when the whole thing has finished executing (IEnumerator&lt;T&gt; supports IDisposable to provide a way to ensure this even when the enumeration is abandoned before it finishes). But this is not okay: try {     Console.WriteLine(&quot;Before&quot;);      yield return 1;  // error CS1626: Cannot yield a value in the body of a try block with a catch clause      Console.WriteLine(&quot;After&quot;); } catch (Exception e) {     Console.WriteLine(e.Message); }  Suppose (for the sake of argument) that an exception is thrown by one or other of the WriteLine calls inside the try block. What's the problem with continuing the execution in catch block? Of course, the yield return part is (currently) unable to throw anything, but why should that stop us from having an enclosing try/catch to deal with exceptions thrown before or after a yield return? Update: There's an  - seems that they already have enough problems implementing the try/finally behaviour correctly! EDIT: The MSDN page on this error is: .  It doesn't explain why, though.
3298
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var?  For example I rather lazily used var in questionable circumstances, e.g.:-  foreach(var item in someList) { // ... } // Type of 'item' not clear. var something = someObject.SomeProperty; // Type of 'something' not clear. var something = someMethod(); // Type of 'something' not clear.   More legitimate uses of var are as follows:-  var l = new List&lt;string&gt;(); // Obvious what l will be. var s = new SomeClass(); // Obvious what s will be.   Interestingly LINQ seems to be a bit of a grey area, e.g.:-  var results = from r in dataContext.SomeTable               select r; // Not *entirely clear* what results will be here.   It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is.  It's even worse when it comes to LINQ to objects, e.g.:-  var results = from item in someList               where item != 3               select item;   This is no better than the equivilent foreach(var item in someList) { // ... } equivilent.  There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable&lt;int&gt; and IEnumerable&lt;double&gt; the caller might inadvertently pass in the wrong type.  var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
7882
What's the best way to convert a string to an enumeration value in C#? I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value. In an ideal world, I could do something like this: StatusEnum MyStatus = StatusEnum.Parse(&quot;Active&quot;);  but that isn't a valid code.
31644
I'm looking for a clear, concise and accurate answer.    Ideally as the actual answer, although links to good explanations welcome.  This also applies to VB.Net, but the keywords are different - ByRef and ByVal.
27821
Can anyone explain IEnumerable and IEnumerator to me? For example, when to use it over foreach? what's the difference between IEnumerable and IEnumerator? Why do we need to use it?
2292
I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was wondering if there was a better way to do it, possibly by using a temp array.  What is the best way to remove duplicates from a C# array?
53785
So, every time I have written a lambda expression or anonymous method inside a method that I did not get quite right, I am forced to recompile and restart the entire application or unit test framework in order to fix it. This is seriously annoying, and I end up wasting more time than I saved by using these constructs in the first place. It is so bad that I try to stay away from them if I can, even though Linq and lambdas are among my favourite C# features.  I suppose there is a good technical reason for why it is this way, and perhaps someone knows? Furthermore, does anyone know if it will be fixed in VS2010?  Thanks.
58355
I have the following code:  MemoryStream foo(){     MemoryStream ms = new MemoryStream();     // write stuff to ms     return ms; }  void bar(){     MemoryStream ms2 = foo();     // do stuff with ms2     return; }   Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later?    I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.
104379
Can I use this approach efficiently?  using(SqlCommand cmd = new SqlCommand("GetSomething", new SqlConnection(Config.ConnectionString)) {     cmd.Connection.Open();     // set up parameters and CommandType to StoredProcedure etc. etc.     cmd.ExecuteNonQuery(); }   My concern is : Will the Dispose method of the SqlCommand (which is called when exiting the using block) close the underlying SqlConnection object or not?
31862
Why are static indexers disallowed in C#? I see no reason why they should not be allowed and furthermore they could be very useful.  For example:  public static class ConfigurationManager  {         public object this[string name]         {             get =&gt; ConfigurationManager.getProperty(name);             set =&gt; ConfigurationManager.editProperty(name, value);         }          /// &lt;summary&gt;         /// This will write the value to the property. Will overwrite if the property is already there         /// &lt;/summary&gt;         /// &lt;param name="name"&gt;Name of the property&lt;/param&gt;         /// &lt;param name="value"&gt;Value to be wrote (calls ToString)&lt;/param&gt;         public static void editProperty(string name, object value)          {             var ds = new DataSet();             var configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);             ds.ReadXml(configFile);              if (ds.Tables["config"] == null)                 ds.Tables.Add("config");              var config = ds.Tables["config"];              if (config.Rows[0] == null)                  config.Rows.Add(config.NewRow());              if (config.Columns[name] == null)                  config.Columns.Add(name);              config.Rows[0][name] = value.ToString();              ds.WriteXml(configFile);             configFile.Close();         }          public static void addProperty(string name, object value) =&gt;             ConfigurationManager.editProperty(name, value);          public static object getProperty(string name)          {             var ds = new DataSet();             var configFile = new FileStream("./config.xml", FileMode.OpenOrCreate);             ds.ReadXml(configFile);             configFile.Close();              if (ds.Tables["config"] == null) return null;              var config = ds.Tables["config"];              if (config.Rows[0] == null) return null;             if (config.Columns[name] == null) return null;              return config.Rows[0][name];         }     }   The above code would benefit greatly from a static indexer. However it won't compile because static indexers are not allowed. Why is this so?
51479
Having read the threads  and  I am wondering for classes such as SqlConnection or one of the several classes inheriting from the Stream class does it matter if I close Dispose rather than Close?
560
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl;   results in Cannot implicitly convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  And then...  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl;   results in Cannot convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
38358
I've been learning C#, and I'm trying to understand lambdas.  In this sample below, it prints out 10 ten times.  class Program {     delegate void Action();     static void Main(string[] args)     {         List&lt;Action&gt; actions = new List&lt;Action&gt;();          for (int i = 0; i &lt; 10; ++i )             actions.Add(()=&gt;Console.WriteLine(i));          foreach (Action a in actions)             a();     } }   Obviously, the generated class behind the lambda is storing a reference or pointer to the int i variable, and is assigning a new value to the same reference every time the loop iterates.  Is there a way to force the lamda to grab a copy instead, like the C++0x syntax  [&amp;](){ ... } // Capture by reference   vs.  [=](){ ... } // Capture copies
20286
I have quickly read over the  documentation.  This kind of example has helped me to understand better, though:   delegate int del(int i); del myDelegate = x =&gt; x * x; int j = myDelegate(5); //j = 25   Still, I don't understand why it's such an innovation. It's just a method that dies when the "method variable" ends, right? Why should I use this instead of a real method?
112156
Is it possible to have a look at all .net objects which are collected upon calling GC.Collect()?  I need to see what objects are still in memory and not reclaimed, so I can find where reclaiming the objects should have done manual, but was forgotten by the programmer. I don't want to call GC.Collect because someone somewhere forgot to dispose an object which blocks some handles.
75124
I often want to grab the first element of an IEnumerable&lt;T&gt; in .net, and I haven't found a nice way to do it.  The best I've come up with is:  foreach(Elem e in enumerable) {   // do something with e   break; }   Yuck!  So, is there a nice way to do this?