I am preparing for my C# EXAM. I am confused about the answer to this question:     A program can use the IEnumerable and IEnumerator interfaces to do which of the following?      a. Use MoveNext and Reset to move through a list of objects.   b. Use foreach to move through a list of objects.   c. Move through a list of objects by index.   d. Use the yield return statement to make a list of objects for iteration.   My answer was b). But the book: MCSD Certification Toolkit says it is a).   Can someone tell me why?  I realize that you can obtain the Enumerator using GetEnumerator() and then call the MoveNext and Reset methods to move through the list (and use Current to access the current element  referred to by the iterator). But isn't implementing IEnumerable and IEnumerator the reason for an object to be used in a foreach loop?
123032
Possible Duplicate:          What are the differences between IEnumerator and IEnumerable?
1080
How can you enumerate an enum in C#?  E.g. the following code does not compile:  public enum Suit {     Spades,     Hearts,     Clubs,     Diamonds }  public void EnumerateAllSuitsDemoMethod() {     foreach (Suit suit in Suit)     {         DoSomething(suit);     } }   And it gives the following compile-time error:     'Suit' is a 'type' but is used like a 'variable'   It fails on the Suit keyword, the second one.
117936
The following throws an InvalidCastException.  IEnumerable&lt;int&gt; list = new List&lt;int&gt;() { 1 }; IEnumerable&lt;long&gt; castedList = list.Cast&lt;long&gt;(); Console.WriteLine(castedList.First());   Why?  I'm using Visual Studio 2008 SP1.
110792
The code looks like below:  namespace Test {     public interface IMyClass     {         List&lt;IMyClass&gt; GetList();     }      public class MyClass : IMyClass     {         public List&lt;IMyClass&gt; GetList()         {             return new List&lt;IMyClass&gt;();         }     } }   When I Run Code Analysis i get the following recommendation.     Warning    3   CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection   How should I fix this and what is good practice here?
29105
Can someone explain to me why in .NET 2.0 if I have an interface, IPackable and a class that implements that interface OrderItem, when I have a method that takes in a List&lt;IPackable&gt;, passing in a list of List&lt;OrderItem&gt; does not work?    Does anyone know how I could accomplish this functionality?  Code:  public interface IPackable {         double Weight{ get; } }  public class OrderItem : IPackable   public List&lt;IShipMethod&gt; GetForShipWeight(List&lt;IPackable&gt; packages) {    double totalWeight = 0;    foreach (IPackable package in packages) {         totalWeight += package.Weight;    } }   The following code does not work.  List&lt;OrderItem&gt; orderItems = new List&lt;OrderItem&gt;(); List&lt;IShipMethod&gt; shipMethods = GetForShipWeight(orderItems);
43660
I have a list of structs and I want to change one element. For example :  MyList.Add(new MyStruct("john"); MyList.Add(new MyStruct("peter");   Now I want to change one element:  MyList[1].Name = "bob"   However, whenever I try and do this I get the following error:     Cannot modify the return value of   System.Collections.Generic.List.this[int]‘ because it is not   a variable   If I use a list of classes, the problem doesn't occur.  I guess the answer has to do with structs being a value type.  So, if I have a list of structs should I treat them as read-only? If I need to change elements in a list then I should use classes and not structs?
31102
The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code.   var urls = new List&lt;string&gt;(); urls.Add("http://www.google.com");  foreach (string url in urls) {     // Get all links from the url     List&lt;string&gt; newUrls = GetLinks(url);      urls.AddRange(newUrls); // &lt;-- This is really the problematic row, adding values to the collection I'm looping }   How can I rewrite this in a better way? I'm guessing a recursive solution?
40365
Is there a way to do the following using LINQ?  foreach (var c in collection) {     c.PropertyToSet = value; }   To clarify, I want to iterate through each object in a collection and then update a property on each object.  My use case is I have a bunch of comments on a blog post, and I want to iterate through each comment on a blog post and set the datetime on the blog post to be +10 hours. I could do it in SQL, but I want to keep it in the business layer.
71175
I need to move backwards through an array, so I have code like this:  for (int i = myArray.Length - 1; i &gt;= 0; i--) {     // Do something     myArray[i] = 42; }   Is there a better way of doing this?  Update: I was hoping that maybe C# had some built-in mechanism for this like:  foreachbackwards (int i in myArray) {     // so easy }   Update 2: There are better ways. Rune takes the prize with:  for (int i = myArray.Length; i-- &gt; 0; ) {         //do something } //or for (int i = myArray.Length; i --&gt; 0; ) {     // do something }   which looks even better in regular C (thanks to Twotymz):  for (int i = lengthOfArray; i--; ) {         //do something }
27544
I would like to use Linq to query a bus schedule in my project, so that at any time I can get the next 5 bus arrival times. How can I limit my query to the first 5 results?  More generally, how can I take a slice of a list in C#? (In Python I would use mylist[:5] to get the first 5 elements.)
76493
I am working on creating an immutable class. I have marked all the properties as read-only.   I have a list of items in the class. Although if the property is read-only the list can be modified.   Exposing the IEnumerable of the list makes it immutable. I wanted to know  what is the basic rules one has to follow to make a class immutable ?
44919
I'm trying to use Linq to return a list of ids given a list of objects where the id is a property. I'd like to be able to do this without looping through each object and pulling out the unique ids that I find.  I have a list of objects of type MyClass and one of the properties of this class is an ID.  public class MyClass {   public int ID { get; set; } }   What I want to do is write a Linq query to return me a list of those Ids  How do I do that given an IList&lt;MyClass&gt; such that it returns an IEnumerable&lt;int&gt; of the ids?  I'm sure it must be possible to do it in one or two lines using Linq rather than looping through each item in the MyClass list and adding the unique values into a list.  Any help in creating an elegant solution would be much appreciated!
105044
This might be a old question: Why does IEnumerable&lt;T&gt; inherit from IEnumerable?  This is how .NET do, but it brings a little trouble. Every time I write a class implements IEumerable&lt;T&gt;, I have to write two GetEnumerator() functions, one for IEnumerable&lt;T&gt; and the other for IEnumerable.  And, IList&lt;T&gt; doesn't inherit from IList.   I don't know why IEnumerable&lt;T&gt; is designed in other way.
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
86447
I love recursion. I think it simplifies things a lot. Another may disagree; I think it also makes the code a lot easier to read. However, I've noticed that recursion is not used as much in languages such C# as they are in LISP (which by the way is my favorite language because of the recursion).   Does anybody know if there is any good reasons not use recursion in the languages such as C#? Is it more expensive than iteration?
1512
I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a BiDictionaryOneToOne&lt;T, S&gt; which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't believe that I'm the first person to need this...  There is a BiDictionary in the answers to , but it is not for unique elements (and also does not implement RemoveByFirst(T t) or RemoveBySecond(S s)).   Thanks!
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.