fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. var foo = new Foo();
  10. foo.GetFoo1().Add("hello! why can I do this??");
  11. Console.WriteLine(string.Join(", ", foo.GetFoo1()));
  12.  
  13. foo.GetFoo2().Add("this won't change the field");
  14. Console.WriteLine(string.Join(", ", foo.GetFoo2()));
  15.  
  16. // Won't compile:
  17. // foo.GetFoo3().Add("??");
  18.  
  19. ((IList<string>) foo.GetFoo3()).Add("This works, but people are unlikely to make this mistake");
  20. Console.WriteLine(string.Join(", ", foo.GetFoo3().ToList()));
  21. }
  22.  
  23. class Foo
  24. {
  25. private readonly List<string> foo = new List<string>();
  26.  
  27. public List<string> GetFoo1()
  28. {
  29. return this.foo;
  30. }
  31.  
  32. public List<string> GetFoo2()
  33. {
  34. return this.foo.ToList();
  35. }
  36.  
  37. public IEnumerable<string> GetFoo3()
  38. {
  39. return this.foo;
  40. }
  41. }
  42. }
Success #stdin #stdout 0.03s 24184KB
stdin
Standard input is empty
stdout
hello! why can I do this??
hello! why can I do this??
hello! why can I do this??, This works, but people are unlikely to make this mistake