ImmutableList.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System.Reactive
  5. {
  6. class ImmutableList<T>
  7. {
  8. T[] data;
  9. public ImmutableList()
  10. {
  11. data = new T[0];
  12. }
  13. public ImmutableList(T[] data)
  14. {
  15. this.data = data;
  16. }
  17. public ImmutableList<T> Add(T value)
  18. {
  19. var newData = new T[data.Length + 1];
  20. Array.Copy(data, newData, data.Length);
  21. newData[data.Length] = value;
  22. return new ImmutableList<T>(newData);
  23. }
  24. public ImmutableList<T> Remove(T value)
  25. {
  26. var i = IndexOf(value);
  27. if (i < 0)
  28. return this;
  29. var newData = new T[data.Length - 1];
  30. Array.Copy(data, 0, newData, 0, i);
  31. Array.Copy(data, i + 1, newData, i, data.Length - i - 1);
  32. return new ImmutableList<T>(newData);
  33. }
  34. public int IndexOf(T value)
  35. {
  36. for (var i = 0; i < data.Length; ++i)
  37. if (data[i].Equals(value))
  38. return i;
  39. return -1;
  40. }
  41. public T[] Data
  42. {
  43. get { return data; }
  44. }
  45. }
  46. }