Skip to content

String.Equals isn't intuitive and forces us to do the OrdinalIgnoreCase thing #14065

Closed as not planned

Description

@shanselman

We're doing a sample and we are FOREVER doing this

if (sort.Equals("Title", StringComparison.OrdinalIgnoreCase))

I think it's time for an overload or an extension that "does the right thing." This is a 10 year old pattern and if the default is wrong (as we tell people to do this) then let's make a better method. Everyone has a version and extension that does this.

Activity

  1. jongalloway commented on Feb 5, 2015

    @jongalloway
    Member

    I agree +10e8

  2. madskristensen commented on Feb 5, 2015

    @madskristensen

    +1

    This drives me nuts and forces me to do multi-line if statements due to very long lines this produces. I hate that. A better and much shorter syntax would be super awesome!

  3. rustd commented on Feb 5, 2015

    @rustd

    the default should really be changed as most apps have to have this check

  4. Bhaal22 commented on Feb 5, 2015

    @Bhaal22

    +1
    Makes me crazy.

  5. csharpfritz commented on Feb 5, 2015

    @csharpfritz

    Agreed - lets help our community by making the framework use the correct pattern by default

  6. joshfree commented on Feb 5, 2015

    @joshfree
    Member

    var oic = StringComparer.OrdinalIgnoreCase;

    if (oic.Equals(sort,"Title"))

  7. ellismg commented on Feb 5, 2015

    @ellismg
    Contributor

    I'm not pushing back against this request, but does someone have a strawman to kick off the design? The best thing I can think of is: EqualsOrdinalIgnoreCase as a method on String. Is this still too long?

  8. shanselman commented on Feb 5, 2015

    @shanselman
    Author

    Why not EqualsIgnoreCase. Is Ordinal that obvious, or needed? (although semantically it would be implied.)

  9. ellismg commented on Feb 5, 2015

    @ellismg
    Contributor

    @shanselman I guess that's reasonable. Personally I dislike how some operations on the string class do linguistic comparisons where as others do ordinal and it's not clear from the method name what's going on. This proposal would be making the problem worse, but perhaps we should optimize for folks that have already learned for each method if it's doing ordinal or linguistic conversions.

  10. shanselman commented on Feb 5, 2015

    @shanselman
    Author

    @ellismg I hear you. I'm trying to optimize for the 80% or even the 90% case. What is the "pit of success" option? What's the one that if folks who don't know the difference pick is more likely to be correct?

  11. plemanach commented on Feb 6, 2015

    @plemanach

    +1 EqualsIgnoreCase

  12. davkean commented on Feb 6, 2015

    @davkean
    Member

    @rustd Are you suggesting that ignore case should be the default? Changing defaults around this is pretty much a non-starter. We've tried similar things in the past (such as switching all operations to ordinal and invariant by default in Silverlight) but ended up backing it out for a variety of reasons. There's just too much legacy code being copied and pasted around.

    I like static bool EqualsIgnoreCase(string, string) and bool EqualsIgnoreCase(string), it fits in with existing overloads static bool Equals(string, string) and bool Equals(string) which already do a ordinal comparison.

  13. ebickle commented on Feb 6, 2015

    @ebickle

    @davkean @shanselman Agree on EqualsIgnoreCase.

    I did a quick scan through the String class, other methods that take a StringComparison overload include Compare, CompareOrdinal, CompareTo, StartsWith, EndsWith, IndexOf, LastIndexOf, Replace. None of them seem like a high priority for an IgnoreCase overload.

    What's painfully missing is a Contains overload that accepts a comparison type. It's a bigger functionality gap than EqualsIngoreCase.

    public bool EqualsIgnoreCase(string value);
    public static bool EqualsIgnoreCase(string a, string b);
    public bool Contains(string value, StringComparison comparisonType);
    

    This may be a bit more of a stretch, a new IStringEquatable interface could be introduced that inherits from IEquatable. IStringEquatable would add the necessary overloads for the comparison type.

    public IStringEquatable<T> : IEquatable<T>
    {
        bool Equals(T other, StringComparison comparisonType);
    }
    

    The C# team is currently looking at potentially implementing pattern matching and improvements to the switch statement for C# 7.0. One source of pain has been the inability to do case insensitive comparisons in a switch statement - introducing the interface would provide a hook for case insensitive comparisons as 'syntactic sugar'. The interface could be added to the other string-like types, such as HtmlString.

    I never quite understood why languages don't introduce a case-insensitive string comparison operator. It's likely that because it only applies to a string, it doesn't meet the bar required for a broadly used language feature. That said, the same was once true for String types themselves (just use an array!). Case-insensitive string comparisons are a very bread & butter development operation, and as noted above can apply to types other than System.String.

    Imagine the theoretical ==~ and !=~ operators (the tilde being the approximation symbol, not bitwise complement):

    public static String overload ==~(String a, String b)
    public static String overload !=~(String a, String b)
    
    if ("CoreFx" ==~ "corefx") // true
    

    Even aside from theoretical language changes (very unlikely), the interface would allow libraries such as LINQ to leverage case-insensitive string equality natively without resorting to reflection. The same holds true for String.Compare, which strangely is missing a non-static String.Compare(string, StringComparison) overload.

  14. shanselman commented on Feb 6, 2015

    @shanselman
    Author

    I love the possible case-insensitive string operators. Until then, let's do
    EqualsIgnoreCase.

    On Fri, Feb 6, 2015 at 10:06 AM, Eric Bickle [email protected]
    wrote:

    @davkean https://github.com/davkean @shanselman
    https://github.com/shanselman Agree on EqualsIgnoreCase.

    public bool EqualsIgnoreCase(string value);
    public static bool EqualsIgnoreCase(string a, string b);

    I did a quick scan through the String class, other methods that take a
    StringComparison overload include Compare, CompareOrdinal, CompareTo,
    StartsWith, EndsWith, IndexOf, LastIndexOf, Replace. None of them seem
    like a high priority for an IgnoreCase overload.

    This may be a bit more of a stretch, a new IStringEquatable interface
    could be introduced that inherits from IEquatable. IStringEquatable would
    add the necessary overloads for the comparison type.

    public IStringEquatable : IEquatable
    {
    bool Equals(T other, StringComparison comparisonType);
    }

    The C# team is currently looking at potentially implementing pattern
    matching and improvements to the switch statement for C# 7.0. One source of
    pain has been the inability to do case insensitive comparisons in a switch
    statement - introducing the interface would provide a hook for case
    insensitive comparisons as 'syntactic sugar'. The interface could be added
    to the other string-like types, such as Char, StringBuilder, and HtmlString.

    I never quite understood why languages don't introduce a case-insensitive
    string comparison operator. It's likely that because it only applies to a
    string the logic is that it doesn't meet the broad use needed for a general
    language feature. That said, the same was once true for String types
    themselves (just use an array!). Case-insensitive string comparisons are a
    very bread & butter development operation, and as noted above can apply to
    types other than System.String.

    Imagine the theoretical ==~ and !=~ operators:

    public static String overload ==(String a, String b)
    public static String overload !=
    (String a, String b)

    if ("CoreFx" ==~ "corefx") // true

    Even aside from theoretical language changes (very unlikely), the
    interface would allow libraries such as LINQ to leverage case-insensitive
    string equality natively without resorting to reflection. The same holds
    true for String.Compare, which strangely is missing a non-static String.Compare(string,
    StringComparison) overload.

    —
    Reply to this email directly or view it on GitHub
    https://github.com/dotnet/corefx/issues/649#issuecomment-73284160.

    Scott Hanselman
    Donate to fight diabetes: http://hnsl.mn/fightdiabetes

  15. 29 remaining items

  16. remcolam commented on Jul 14, 2019

    @remcolam

    My personal solution would be to throw our the StringComparison enum completely, and replace all its uses with the StringComparer static instances. All methods that take StringComparison can easily be rewritten using this.

    The big issue is that you always need a second to thing about which one of the two you need. The typing is not the problem, that's what intellisense/autocomplete is for

  17. Gnbrkm41 commented on Aug 20, 2019

    @Gnbrkm41
    Contributor

    Summarising all the ideas & slipping my cent in :^)

    I think it's fair to provide static versions of the methods as well since we have them for all the other overloads/methods.

    1. Providing an overload of Equals(string) that takes an additional boolean parameter ignoreCase

    Suggested API addition

    public sealed class String
    {
        public string Equals(string str, bool ignoreCase);
        public static string Equals(string a, string b, bool ignoreCase);
    }

    Pros

    • Matches what other methods do, such as IndexOf, Contains, EndsWith, Compare etc

    Cons

    • Overloads of other methods that accept bool does not indicate culture insensitive comparison, but only case sensitivity... though, it might be fine in this instance since string.Equals is ordinal by default.

    Usage

    if (str1.Equals(str2, true))
    {
        // The two strings are considered equal, disregarding culture/case
    }

    2. Providing a new method EqualsIgnoreCase(string)

    Suggested API addition

    public sealed class String
    {
        public string EqualsIgnoreCase(string value);
        public static string EqualsIgnoreCase(string a, string b);
    }

    Pros

    • Maybe... shorter to type?

    Cons

    • Same as the disadvantage described in Issue - corefx#1; implied culture insensitivity.
    • Missing the matching culture sensitive alternative, What if I want to do culture sensitive / case insensitive comparison?

    Usage

    if (str1.EqualsIgnoreCase(str2))
    {
        // ...
    }

    3. Providing a new method EqualsOrdinalIgnoreCase(string)

    Suggested API addition

    public sealed class String
    {
        public string EqualsOrdinalIgnoreCase(string value);
        public static string EqualsOrdinalIgnoreCase(string a, string b);
    }

    Pros

    • Being explicit about both the culture/case insensitivity

    Cons

    • About as long to type

    Usage

    if (str1.EqualsOrdinalIgnoreCase(str2))
    {
    // ...
    }

    4. Providing a new method EqualsOrdinal that takes a string, and an overload that takes an additional parameter ignoreCase. Also an additional Equals(string, bool) overload

    Suggested API addition

    public sealed class String
    {
        public string Equals(string value, bool ignoreCase);
        public static string Equals(string a, string b, bool ignoreCase);
        public string EqualsOrdinal(string value);
        public string EqualsOrdinal(string value, bool ignoreCase);
        public static string EqualsOrdinal(string a, string b);
        public static string EqualsOrdinal(string a, string b, bool ignoreCase);
    }

    (Maybe ignoreCase can be optional?)

    Pros

    ~~+ Matches what other methods do, by providing a bool ignoreCase parameter ~~
    + Matches how Compare has a separate method group dedicated for culture insensitive comparison (Compare and CompareOrdinal, although CompareOrdinal has no instance methods)
    + Explicit about culture insensitivity, which solves the disadvantage described above
    + Also provides easy culture insensitive/case sensitive comparison

    Cons

    - To be discussed

    Usage

    if (str1.EqualsOrdinal(str2, true))
    {
        // The two strings are considered equal, disregarding culture/case
    }

    Apparently I was thinking that string.Equals(string) defaults to current culture when its not. 😅

    Existing alternatives

    1. using the current string.Equals(string, StringComparison)

    if (str1.Equals(str2, StringComparison.OrdinalIgnoreCase))
    {
        // ...
    }

    2. Using StringComparer (Suggested by @\andersstorhaug)

    using static System.StringComparer;
    if (OrdinalIgnoreCase.Equals(alpha, beta))
    { 
        // ...
    }
  18. iSazonov commented on Aug 28, 2019

    @iSazonov
    Contributor

    Adding EqualsIgnoreCase() will add more complicity and open a way for bugs I believe.
    In PowerShell repo we came to always use explicit values for string comparisons. PowerShell is almost always case-insensitive but not always. It uses currentculture for console output but invariant culture or sometimes ordinal in engine. Therefore, we must be careful and always use explicit values so that a code read will always see design intentions. I think it is true for every considerable application.

  19. transferred this issue fromdotnet/corefxon Jan 31, 2020
  20. added this to the 5.0 milestone on Jan 31, 2020
  21. added
    untriaged
    on Feb 23, 2020
  22. modified the milestones: 5.0.0, Future on Jul 6, 2020
  23. removed
    untriaged
    on Jul 6, 2020
  24. GrabYourPitchforks commented on Sep 29, 2020

    @GrabYourPitchforks
    Member

    This issue is going on six years old and has not had any activity in over a year. We're clearly not going to change the behavior of the existing string.Equals or string.operator== APIs.

    The proposal that got the most upvotes in this issue was introducing an EqualsIgnoreCase API, but even that spawned a bit of disagreement.

    There are allusions to more fundamental problems with the string APIs and equality checking, but as far as I can tell nobody in this thread has articulated them. If somebody wants to take a stab at clearly explaining the problem, that would help us properly address this issue.

    Is the problem that we'd prefer the default equality check be ordinal case-insensitive instead of ordinal case-sensitive? (This isn't going to happen.) Is the problem that other string APIs are culture-aware by default? (That's not really relevant to an accelerator for EqualsIgnoreCase.) Is the problem that this is just too much typing and there needs to be an accelerator? (We could address that at an API level or at a language level.)

    As an example of a language accelerator that requires no API additions, there's always:

    using static System.StringComparison;
    
    string candidate = ...;
    if (candidate.Equals("hello", OrdinalIgnoreCase)) { /* do something */ }

    If the goal is to avoid writing the literal text StringComparison more than once per file, does this solve the issue? Without a clearly articulated problem statement, this issue is not currently actionable and is likely to be closed.

  25. divega commented on Sep 30, 2021

    @divega
    Contributor

    I get how adding a case-insensitive version of Equals or an accelerator could help reduce friction in some cases, but what I'm really looking for is a way to let developers control how regular Equals behaves.

    Specifically, being able to make Equals and GetHashCode case-insensitive for certain string members in record types would cut down a lot of friction in the projects I’m working on (control plane of Azure services).

    Without that, unfortunately, I cannot take advantage of records at all.

    Here are a few options I’ve thought of:

    1. A case-insensitive String type (e.g., OrdinalIgnoreCaseString) with literal support and implicit conversion to regular String.
    2. Extending String to allow setting a default comparer at creation time, with fallback rules when strings with different comparers are compared.
    3. Annotating string members (or other elements) with attributes to hint which comparer should be used by the compiler in Equals and GetHashCode generation, and potentially by any framework working with the class.
    4. Rolling my own type that wraps a string.

    Each has its tradeoffs, but I think (3) hits the sweet spot for what I need. It’s less heavy-handed than (1) or (2), and much cleaner than (4).

    Some tradeoffs I see with (3):

    • Since case-sensitivity isn’t tied to the type or carried in the value, that context is lost once the string is assigned to a regular variable. That might surprise some folks.
    • If (3) is too flexible, it could lead to codegen failures or runtime issues. For example, if the compiler pattern-matches a method on the attribute to obtain a comparer, a poorly implemented or misplaced attribute could return the wrong comparer. Not exactly new territory—records can already have tricky custom members—but this adds new ways for even simple members to break.
  26. molinch commented on Nov 3, 2022

    @molinch

    Finding a consensus here might be pretty hard.
    Why not going a completely different direction and having a project level switch? For example:
    <DefaultStringComparison>Ordinal</DefaultStringComparison>

    This would allow people to opt-in to their desired comparer really per project.
    In our projects we keep speficying the comparer absolutely ALL the time, and if we forget the proper comparer we introduce a bug.

    For sure analyzers can solve this, but having to type extra characters all the time to get the proper behavior is just a pain (especially when that behavior should be the default). Furthermore as @divega said, without a solution records are just useless in many scenarios.

    Implementation wise, Roslyn could probably do the heavy lifting and inject the comparer in all ctors/methods that expect a StringComparison/StringComparer.

  27. tannergooding commented on Jul 23, 2026

    @tannergooding
    Member

    Closing as per #14065 (comment)

  28. locked and limited conversation to collaborators on Aug 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions