Guest User

Untitled

a guest
Aug 20th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. Why does calling Enumerable.First() appear to return a copy of the first item in the enumeration
  2. public class Thing
  3. {
  4. public bool Updated { get; set; }
  5.  
  6. public string Name { get; private set; }
  7.  
  8. public Thing(string name)
  9. {
  10. Name = name;
  11. }
  12.  
  13. public override string ToString()
  14. {
  15. return string.Format("{0} updated {1} {2}", Name, Updated, GetHashCode());
  16. }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. Console.WriteLine("IEnumerable<Thing>");
  24. var enumerableThings = GetThings();
  25. var firstThing = enumerableThings.First();
  26. firstThing.Updated = true;
  27. Console.WriteLine("Updated {0}", firstThing);
  28. foreach (var t in enumerableThings)
  29. Console.WriteLine(t);
  30.  
  31. Console.WriteLine("IList<Thing>");
  32. var thingList = GetThings().ToList();
  33. var thing1 = thingList.First();
  34. thing1.Updated = true;
  35. Console.WriteLine("Updated {0}", thing1);
  36. foreach (var t in thingList)
  37. Console.WriteLine(t);
  38.  
  39. Console.ReadLine();
  40. }
  41.  
  42. private static IEnumerable<Thing> GetThings()
  43. {
  44. for (int i = 1; i <= 3; i++)
  45. {
  46. yield return new Thing(string.Format("thing {0}", i));
  47. }
  48. }
  49. }
  50. }
  51.  
  52. IEnumerable<Thing>
  53. Updated thing 1 updated True 37121646
  54. thing 1 updated False 45592480
  55. thing 2 updated False 57352375
  56. thing 3 updated False 2637164
  57. IList<Thing>
  58. Updated thing 1 updated True 41014879
  59. thing 1 updated True 41014879
  60. thing 2 updated False 3888474
  61. thing 3 updated False 25209742
  62.  
  63. IEnumerable<Thing>
  64. Updated thing 1 updated True 45592480
  65. thing 1 updated False 45592480
  66. thing 2 updated False 57352375
  67. thing 3 updated False 2637164
  68. IList<Thing>
  69. Updated thing 1 updated True 41014879
  70. thing 1 updated True 41014879
  71. thing 2 updated False 3888474
  72. thing 3 updated False 25209742
Add Comment
Please, Sign In to add comment