You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
String.Equals isn't intuitive and forces us to do the OrdinalIgnoreCase thing #14065
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.
Reacted by Chris Marisic, Andrew Harper, Michael Ovchinnikov, Joseph Musser, nopara73, nil4, Stano Peťko, Jared Nance, Glenn Slayden, KLuuKer and 13 more
Reacted by LeaFrock, Vyacheslav Brevnov and Cole Tobin
Reacted by Paul Chen, Andrew Harper and Samuel Kelemen
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!
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?
@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.
@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?
@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.
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.
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.
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.
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.
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
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)
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
~~+ 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)
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.
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:
usingstaticSystem.StringComparison;stringcandidate=...;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.
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:
A case-insensitive String type (e.g., OrdinalIgnoreCaseString) with literal support and implicit conversion to regular String.
Extending String to allow setting a default comparer at creation time, with fallback rules when strings with different comparers are compared.
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.
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.
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.
Reacted by Simon Cropp
Reacted by Chris/0, aarondel4, Cole Tobin, Simon Felix and Jeremy Caney
Activity
jongalloway commentedon Feb 5, 2015
I agree +10e8
madskristensen commentedon Feb 5, 2015
+1
This drives me nuts and forces me to do multi-line
ifstatements due to very long lines this produces. I hate that. A better and much shorter syntax would be super awesome!rustd commentedon Feb 5, 2015
the default should really be changed as most apps have to have this check
Bhaal22 commentedon Feb 5, 2015
+1
Makes me crazy.
csharpfritz commentedon Feb 5, 2015
Agreed - lets help our community by making the framework use the correct pattern by default
joshfree commentedon Feb 5, 2015
var oic = StringComparer.OrdinalIgnoreCase;
if (oic.Equals(sort,"Title"))
ellismg commentedon Feb 5, 2015
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?
shanselman commentedon Feb 5, 2015
Why not EqualsIgnoreCase. Is Ordinal that obvious, or needed? (although semantically it would be implied.)
ellismg commentedon Feb 5, 2015
@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.
shanselman commentedon Feb 5, 2015
@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?
plemanach commentedon Feb 6, 2015
+1 EqualsIgnoreCase
davkean commentedon Feb 6, 2015
@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)andbool EqualsIgnoreCase(string), it fits in with existing overloads static boolEquals(string, string)andbool Equals(string)which already do a ordinal comparison.ebickle commentedon Feb 6, 2015
@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.
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.
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):
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.shanselman commentedon Feb 6, 2015
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:
Scott Hanselman
Donate to fight diabetes: http://hnsl.mn/fightdiabetes
29 remaining items
remcolam commentedon Jul 14, 2019
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
Gnbrkm41 commentedon Aug 20, 2019
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
ignoreCaseSuggested API addition
Pros
IndexOf,Contains,EndsWith,CompareetcCons
string.Equalsis ordinal by default.Usage
2. Providing a new method
EqualsIgnoreCase(string)Suggested API addition
Pros
Cons
Usage
3. Providing a new method
EqualsOrdinalIgnoreCase(string)Suggested API addition
Pros
Cons
Usage
4. Providing a new methodEqualsOrdinalthat takes a string, and an overload that takes an additional parameterignoreCase. Also an additionalEquals(string, bool)overloadSuggested API addition(MaybeignoreCasecan be optional?)Pros~~+ Matches what other methods do, by providing a
bool ignoreCaseparameter ~~+ Matches howComparehas a separate method group dedicated for culture insensitive comparison (CompareandCompareOrdinal, although CompareOrdinal has no instance methods)+ Explicit about culture insensitivity, which solves the disadvantage described above+ Also provides easy culture insensitive/case sensitive comparisonCons- To be discussedUsageApparently I was thinking that
string.Equals(string)defaults to current culture when its not. 😅Existing alternatives
1. using the current
string.Equals(string, StringComparison)2. Using StringComparer (Suggested by @\andersstorhaug)
iSazonov commentedon Aug 28, 2019
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.
GrabYourPitchforks commentedon Sep 29, 2020
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.Equalsorstring.operator==APIs.The proposal that got the most upvotes in this issue was introducing an
EqualsIgnoreCaseAPI, 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:
If the goal is to avoid writing the literal text
StringComparisonmore 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.divega commentedon Sep 30, 2021
I get how adding a case-insensitive version of
Equalsor an accelerator could help reduce friction in some cases, but what I'm really looking for is a way to let developers control how regularEqualsbehaves.Specifically, being able to make
EqualsandGetHashCodecase-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:
Stringtype (e.g.,OrdinalIgnoreCaseString) with literal support and implicit conversion to regularString.Stringto allow setting a default comparer at creation time, with fallback rules when strings with different comparers are compared.EqualsandGetHashCodegeneration, and potentially by any framework working with the class.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):
molinch commentedon Nov 3, 2022
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.
tannergooding commentedon Jul 23, 2026
Closing as per #14065 (comment)