CompatibleComparer.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. #nullable enable
  5. #pragma warning disable 618 // obsolete types
  6. namespace System.Collections
  7. {
  8. internal sealed class CompatibleComparer : IEqualityComparer
  9. {
  10. private readonly IHashCodeProvider? _hcp;
  11. private readonly IComparer? _comparer;
  12. internal CompatibleComparer(IHashCodeProvider? hashCodeProvider, IComparer? comparer)
  13. {
  14. _hcp = hashCodeProvider;
  15. _comparer = comparer;
  16. }
  17. internal IHashCodeProvider? HashCodeProvider => _hcp;
  18. internal IComparer? Comparer => _comparer;
  19. public new bool Equals(object? a, object? b) => Compare(a, b) == 0;
  20. public int Compare(object? a, object? b)
  21. {
  22. if (a == b)
  23. return 0;
  24. if (a == null)
  25. return -1;
  26. if (b == null)
  27. return 1;
  28. if (_comparer != null)
  29. {
  30. return _comparer.Compare(a, b);
  31. }
  32. if (a is IComparable ia)
  33. {
  34. return ia.CompareTo(b);
  35. }
  36. throw new ArgumentException(SR.Argument_ImplementIComparable);
  37. }
  38. public int GetHashCode(object obj)
  39. {
  40. if (obj == null)
  41. {
  42. throw new ArgumentNullException(nameof(obj));
  43. }
  44. return _hcp != null ?
  45. _hcp.GetHashCode(obj) :
  46. obj.GetHashCode();
  47. }
  48. }
  49. }