ReadOnlyCollection.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // Author:
  3. // Jb Evain (jbevain@gmail.com)
  4. //
  5. // Copyright (c) 2008 - 2015 Jb Evain
  6. // Copyright (c) 2008 - 2011 Novell, Inc.
  7. //
  8. // Licensed under the MIT/X11 license.
  9. //
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. namespace Mono.Collections.Generic {
  14. public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IList {
  15. static ReadOnlyCollection<T> empty;
  16. public static ReadOnlyCollection<T> Empty {
  17. get { return empty ?? (empty = new ReadOnlyCollection<T> ()); }
  18. }
  19. bool ICollection<T>.IsReadOnly {
  20. get { return true; }
  21. }
  22. bool IList.IsFixedSize {
  23. get { return true; }
  24. }
  25. bool IList.IsReadOnly {
  26. get { return true; }
  27. }
  28. ReadOnlyCollection ()
  29. {
  30. }
  31. public ReadOnlyCollection (T [] array)
  32. {
  33. if (array == null)
  34. throw new ArgumentNullException ();
  35. Initialize (array, array.Length);
  36. }
  37. public ReadOnlyCollection (Collection<T> collection)
  38. {
  39. if (collection == null)
  40. throw new ArgumentNullException ();
  41. Initialize (collection.items, collection.size);
  42. }
  43. void Initialize (T [] items, int size)
  44. {
  45. this.items = new T [size];
  46. Array.Copy (items, 0, this.items, 0, size);
  47. this.size = size;
  48. }
  49. internal override void Grow (int desired)
  50. {
  51. throw new InvalidOperationException ();
  52. }
  53. protected override void OnAdd (T item, int index)
  54. {
  55. throw new InvalidOperationException ();
  56. }
  57. protected override void OnClear ()
  58. {
  59. throw new InvalidOperationException ();
  60. }
  61. protected override void OnInsert (T item, int index)
  62. {
  63. throw new InvalidOperationException ();
  64. }
  65. protected override void OnRemove (T item, int index)
  66. {
  67. throw new InvalidOperationException ();
  68. }
  69. protected override void OnSet (T item, int index)
  70. {
  71. throw new InvalidOperationException ();
  72. }
  73. }
  74. }