2
0

CompatibleComparer.cs 1.6 KB

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