2
0

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. #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. IComparable ia = a as IComparable;
  32. if (ia != null)
  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. }