Skip to content

Proposal: Make it easier to use StringComparison & StringComparer with GetHashCode. #19413

@jamesqo

Description

@jamesqo

Proposed API

  1. Add API to convert a StringComparison to a StringComparer, to avoid bunch of switch-statements in user code (see 'Motivation' section below).
  2. Add string.GetHashCode(StringComparison) API, to make it easier/more discoverable to get the culture-dependent, case-insensitive, etc. hash of a string. Currently, you have to do StringComparer.XXX.GetHashCode(str), which is verbose & hard to find.
public class StringComparer
{
    public static StringComparer FromComparison(StringComparison comparisonType);
}

public sealed class String
{
    public int GetHashCode(StringComparison comparisonType);
}

Motivation

If someone has a variable comparison they don't have to do a bunch of switch-cases (we'll do them instead):

    public static StringComparer FromComparison(StringComparison comparisonType)
    {
        switch (comparisonType)
        {
            case StringComparison.Ordinal:
                return StringComparer.Ordinal;
            case StringComparison.OrdinalIgnoreCase:
                return StringComparer.OrdinalIgnoreCase;
                ...
        }
    }

For more background: See @stephentoub's suggestion in https://github.com/dotnet/corefx/issues/8034#issuecomment-261519913

cc @justinvp @elion

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Runtimehelp wanted[up-for-grabs] Good issue for external contributorswishlistIssue we would like to prioritize, but we can't commit we will get to it yet

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions