CaseInsensitiveHashCodeProvider.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // System.Collections.CaseInsensitiveHashCodeProvider.cs
  3. //
  4. // Authors:
  5. // Sergey Chaban ([email protected])
  6. // Andreas Nahr ([email protected])
  7. //
  8. using System.Globalization;
  9. namespace System.Collections
  10. {
  11. [Serializable]
  12. public class CaseInsensitiveHashCodeProvider : IHashCodeProvider
  13. {
  14. static readonly CaseInsensitiveHashCodeProvider singleton = new CaseInsensitiveHashCodeProvider ();
  15. static readonly CaseInsensitiveHashCodeProvider singletonInvariant = new CaseInsensitiveHashCodeProvider (true);
  16. CultureInfo culture;
  17. // Public instance constructor
  18. public CaseInsensitiveHashCodeProvider ()
  19. {
  20. culture = CultureInfo.CurrentCulture;
  21. }
  22. private CaseInsensitiveHashCodeProvider (bool invariant)
  23. {
  24. // leave culture == null
  25. }
  26. public CaseInsensitiveHashCodeProvider (CultureInfo culture)
  27. {
  28. if (culture == null)
  29. throw new ArgumentNullException ("culture");
  30. if (culture.LCID != CultureInfo.InvariantCulture.LCID)
  31. this.culture = culture;
  32. // else leave culture == null
  33. }
  34. //
  35. // Public static properties
  36. //
  37. public static CaseInsensitiveHashCodeProvider Default {
  38. get {
  39. return singleton;
  40. }
  41. }
  42. #if NET_1_1
  43. public
  44. #else
  45. internal
  46. #endif
  47. static CaseInsensitiveHashCodeProvider DefaultInvariant {
  48. get {
  49. return singletonInvariant;
  50. }
  51. }
  52. //
  53. // IHashCodeProvider
  54. //
  55. public int GetHashCode (object obj)
  56. {
  57. if (obj == null)
  58. throw new ArgumentNullException ("obj");
  59. string str = obj as string;
  60. if (str == null)
  61. return obj.GetHashCode ();
  62. int h = 0;
  63. char c;
  64. if (culture != null) {
  65. for (int i = 0; i < str.Length; i++) {
  66. c = Char.ToLower (str [i], culture);
  67. h = h * 31 + c;
  68. }
  69. }
  70. else {
  71. for (int i = 0; i < str.Length; i++) {
  72. c = Char.ToLowerInvariant (str [i]);
  73. h = h * 31 + c;
  74. }
  75. }
  76. return h;
  77. }
  78. }
  79. }