code_junkie

Are there any good reasons why closures aren't immutable in C#

Nov 13th, 2011
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. var foo = "hello";
  2. Action bar = () => Console.WriteLine(foo);
  3. bar();
  4. foo = "goodbye";
  5. bar();
  6.  
  7. class Foo
  8. {
  9. public string Text;
  10. }
  11. var foo = new Foo();
  12. foo.Text = "Hello";
  13. Action bar = () => Console.WriteLine(foo.Text);
  14. bar();
  15. foo.Text = "goodbye";
  16. bar();
  17.  
  18. [CompilerGenerated]
  19. private sealed class <>c__DisplayClass1
  20. {
  21. public string foo;
  22.  
  23. public void <Main>b__0()
  24. {
  25. Console.WriteLine(this.foo);
  26. }
  27. }
  28.  
  29. var foo = "hello";
  30. Action bar = [readonly foo]() => Console.WriteLine(foo);
  31. bar();
  32. foo = "goodbye";
  33. bar();
  34.  
  35. [CompilerGenerated]
  36. private sealed class <>c__DisplayClass1
  37. {
  38. public readonly string foo;
  39.  
  40. public <>c__DisplayClass1(string foo)
  41. {
  42. this.foo = foo;
  43. }
  44.  
  45. public void <Main>b__0()
  46. {
  47. Console.WriteLine(this.foo);
  48. }
  49. }
  50.  
  51. using System;
  52. using System.Collections.Generic;
  53. using System.Linq;
  54. using System.Text;
  55.  
  56. namespace ClosureTest
  57. {
  58. class Program
  59. {
  60. static void Main(string[] args)
  61. {
  62. string userFilter = "C";
  63. IEnumerable<string> query = (from m in typeof(String).GetMethods()
  64. where m.Name.StartsWith(userFilter)
  65. select m.Name.ToString()).Distinct();
  66.  
  67. while(userFilter.ToLower() != "q")
  68. {
  69. DiplayStringMethods(query, userFilter);
  70. userFilter = GetNewFilter();
  71. }
  72. }
  73.  
  74. static void DiplayStringMethods(IEnumerable<string> methodNames, string userFilter)
  75. {
  76. Console.WriteLine("Here are all of the String methods starting with the letter "{0}":", userFilter);
  77. Console.WriteLine();
  78.  
  79. foreach (string methodName in methodNames)
  80. Console.WriteLine(" * {0}", methodName);
  81. }
  82.  
  83. static string GetNewFilter()
  84. {
  85. Console.WriteLine();
  86. Console.Write("Enter a new starting letter (type "Q" to quit): ");
  87. ConsoleKeyInfo cki = Console.ReadKey();
  88. Console.WriteLine();
  89. return cki.Key.ToString();
  90. }
  91. }
  92. }
  93.  
  94. string userFilter = "C";
  95. string userFilter_copy = userFilter;
  96. IEnumerable<string> query = (from m in typeof(String).GetMethods()
  97. where m.Name.StartsWith(userFilter_copy)
  98. select m.Name.ToString()).Distinct();
Add Comment
Please, Sign In to add comment