Index.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. namespace System
  5. {
  6. public readonly struct Index : IEquatable<Index>
  7. {
  8. private readonly int _value;
  9. public Index(int value, bool fromEnd)
  10. {
  11. if (value < 0)
  12. {
  13. ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException();
  14. }
  15. _value = fromEnd ? ~value : value;
  16. }
  17. public int Value => _value < 0 ? ~_value : _value;
  18. public bool FromEnd => _value < 0;
  19. public override bool Equals(object value) => value is Index && _value == ((Index)value)._value;
  20. public bool Equals (Index other) => _value == other._value;
  21. public override int GetHashCode()
  22. {
  23. return _value;
  24. }
  25. public override string ToString()
  26. {
  27. string str = Value.ToString();
  28. return FromEnd ? "^" + str : str;
  29. }
  30. public static implicit operator Index(int value)
  31. => new Index(value, fromEnd: false);
  32. }
  33. }