Guest User

Untitled

a guest
Jun 22nd, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. class A
  2. {
  3. // Note: List is just example, I am interested in objects in general.
  4. private List<string> _items = new List<string>() { "hello" }
  5.  
  6. public List<string> Items
  7. {
  8. get
  9. {
  10. // Option A (not read-only), can be modified from outside:
  11. return _items;
  12.  
  13. // Option B (sort-of read-only):
  14. return new List<string>( _items );
  15.  
  16. // Option C, must change return type to ReadOnlyCollection<string>
  17. return new ReadOnlyCollection<string>( _items );
  18. }
  19. }
  20. }
  21.  
  22. List<string> someList = ( new A() ).Items;
  23.  
  24. public class A
  25. {
  26. private int _n;
  27. public int N
  28. {
  29. get { return _n; }
  30. set { _n = value; }
  31. }
  32. }
  33.  
  34. public interface IReadOnlyA
  35. {
  36. public int N { get; }
  37. }
  38. public class A : IReadOnlyA
  39. {
  40. private int _n;
  41. public int N
  42. {
  43. get { return _n; }
  44. set { _n = value; }
  45. }
  46. }
Add Comment
Please, Sign In to add comment