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.
6 using System.Diagnostics;
7 using System.Diagnostics.Contracts;
9 namespace System.Globalization
11 public static class GlobalizationExtensions
13 public static StringComparer GetStringComparer(this CompareInfo compareInfo, CompareOptions options)
15 if (compareInfo == null)
17 throw new ArgumentNullException(nameof(compareInfo));
20 if (options == CompareOptions.Ordinal)
22 return StringComparer.Ordinal;
25 if (options == CompareOptions.OrdinalIgnoreCase)
27 return StringComparer.OrdinalIgnoreCase;
30 if ((options & CultureAwareComparer.ValidCompareMaskOffFlags) != 0)
32 throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
35 return new CultureAwareComparer(compareInfo, options);
39 internal sealed class CultureAwareComparer : StringComparer
41 internal const CompareOptions ValidCompareMaskOffFlags =
42 ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
43 CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
45 private readonly CompareInfo _compareInfo;
46 private readonly CompareOptions _options;
48 internal CultureAwareComparer(CompareInfo compareInfo, CompareOptions options)
50 Debug.Assert((options & ValidCompareMaskOffFlags) == 0);
51 _compareInfo = compareInfo;
55 public override int Compare(string x, string y)
57 if (Object.ReferenceEquals(x, y)) return 0;
58 if (x == null) return -1;
59 if (y == null) return 1;
60 return _compareInfo.Compare(x, y, _options);
63 public override bool Equals(string x, string y)
65 if (Object.ReferenceEquals(x, y)) return true;
66 if (x == null || y == null) return false;
68 return (_compareInfo.Compare(x, y, _options) == 0);
71 public override int GetHashCode(string obj)
75 throw new ArgumentNullException(nameof(obj));
77 Contract.EndContractBlock();
79 // StringSort used in compare operation and not with the hashing
80 return _compareInfo.GetHashCode(obj, _options & (~CompareOptions.StringSort));
83 // Equals method for the comparer itself.
84 public override bool Equals(object obj)
86 CultureAwareComparer comparer = obj as CultureAwareComparer;
89 _options == comparer._options &&
90 _compareInfo.Equals(comparer._compareInfo);
93 public override int GetHashCode()
95 return _compareInfo.GetHashCode() ^ ((int)_options & 0x7FFFFFFF);