From b497978fbdbc337376253b41b56776bd279917d2 Mon Sep 17 00:00:00 2001 From: Alexander Radchenko Date: Fri, 16 Dec 2016 06:24:14 +0700 Subject: [PATCH] Make it easier to use StringComparison & StringComparer with GetHashCode (#8633) * Make it easier to use StringComparison & StringComparer with GetHashCode * model.xml --- src/mscorlib/model.xml | 2 ++ src/mscorlib/src/System/String.Comparison.cs | 5 +++++ src/mscorlib/src/System/StringComparer.cs | 22 ++++++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/src/mscorlib/model.xml b/src/mscorlib/model.xml index afc6af1f4c..31b00eb867 100644 --- a/src/mscorlib/model.xml +++ b/src/mscorlib/model.xml @@ -7393,6 +7393,7 @@ + @@ -7500,6 +7501,7 @@ + diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs index da991706f8..07f2f9de22 100644 --- a/src/mscorlib/src/System/String.Comparison.cs +++ b/src/mscorlib/src/System/String.Comparison.cs @@ -997,6 +997,11 @@ namespace System return GetLegacyNonRandomizedHashCode(); } + // Gets a hash code for this string and this comparison. If strings A and B and comparition C are such + // that String.Equals(A, B, C), then they will return the same hash code with this comparison C. + [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] + public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this); + // Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile // hash table). [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] diff --git a/src/mscorlib/src/System/StringComparer.cs b/src/mscorlib/src/System/StringComparer.cs index af0b595855..02e8d71d0e 100644 --- a/src/mscorlib/src/System/StringComparer.cs +++ b/src/mscorlib/src/System/StringComparer.cs @@ -62,6 +62,28 @@ namespace System { } } + // Convert a StringComparison to a StringComparer + public static StringComparer FromComparison(StringComparison comparisonType) + { + switch (comparisonType) + { + case StringComparison.CurrentCulture: + return CurrentCulture; + case StringComparison.CurrentCultureIgnoreCase: + return CurrentCultureIgnoreCase; + case StringComparison.InvariantCulture: + return InvariantCulture; + case StringComparison.InvariantCultureIgnoreCase: + return InvariantCultureIgnoreCase; + case StringComparison.Ordinal: + return Ordinal; + case StringComparison.OrdinalIgnoreCase: + return OrdinalIgnoreCase; + default: + throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType)); + } + } + public static StringComparer Create(CultureInfo culture, bool ignoreCase) { if( culture == null) { throw new ArgumentNullException(nameof(culture)); -- 2.34.1