The Labs \ Source Viewer \ SSCLI \ System.Collections \ CompatibleComparer

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. namespace System.Collections
  16. {
  17.    
  18.     [Serializable()]
  19.     internal class CompatibleComparer : IEqualityComparer
  20.     {
  21.         IComparer _comparer;
  22.         #pragma warning disable 618
  23.         IHashCodeProvider _hcp;
  24.        
  25.         internal CompatibleComparer(IComparer comparer, IHashCodeProvider hashCodeProvider)
  26.         {
  27.             _comparer = comparer;
  28.             _hcp = hashCodeProvider;
  29.         }
  30.         #pragma warning restore 618
  31.        
  32.         public int Compare(object a, object b)
  33.         {
  34.             if (a == b)
  35.                 return 0;
  36.             if (a == null)
  37.                 return -1;
  38.             if (b == null)
  39.                 return 1;
  40.             if (_comparer != null)
  41.                 return _comparer.Compare(a, b);
  42.             IComparable ia = a as IComparable;
  43.             if (ia != null)
  44.                 return ia.CompareTo(b);
  45.            
  46.             throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
  47.         }
  48.        
  49.         public new bool Equals(object a, object b)
  50.         {
  51.             return Compare(a, b) == 0;
  52.         }
  53.        
  54.         public int GetHashCode(object obj)
  55.         {
  56.             if (obj == null) {
  57.                 throw new ArgumentNullException("obj");
  58.             }
  59.            
  60.             if (_hcp != null)
  61.                 return _hcp.GetHashCode(obj);
  62.             return obj.GetHashCode();
  63.         }
  64.        
  65.         // These are helpers for the Hashtable to query the IKeyComparer infrastructure.
  66.         internal IComparer Comparer {
  67.             get { return _comparer; }
  68.         }
  69.        
  70.         // These are helpers for the Hashtable to query the IKeyComparer infrastructure.
  71.         #pragma warning disable 618
  72.         internal IHashCodeProvider HashCodeProvider {
  73.             get { return _hcp; }
  74.         }
  75.         #pragma warning restore 618
  76.     }
  77. }

Developer Fusion