Which string comparer is used with switch statements?
Asked Answered
U

1

6

How are strings compared when doing switch statements? Does the current culture of the thread / computer affect switch evaluation? I got in the habit of always specifying a comparer when comparing strings, so it would be great to have this confirmed.

I suspect it's StringComparer.Ordinal, but I cannot find any documentation on this.

Unzip answered 18/8, 2019 at 13:21 Comment(1)
See source : referencesource.microsoft.com/#System/compmod/system/…Impearl
E
6

Does the current culture of the thread / computer affect switch evaluation?

No, it does not.

switch, uses Equals under the covers. Thus it is ordinal:

This method performs an ordinal (case-sensitive and culture-insensitive) comparison.

How do we know switch uses Equals? Well the docs state:

The constant expression is evaluated as follows:

  • If expr and constant are integral types, the C# equality operator determines whether the expression returns true (that is, whether expr == constant).

  • Otherwise, the value of the expression is determined by a call to the static Object.Equals(expr, constant) method.

The latter bullet point is what applies here.

Estrus answered 18/8, 2019 at 13:27 Comment(2)
So, it is not literally using StringComparer.Ordinal but it is doing that same comparison.Unzip
Effectively yes @DavidS. Although referencesource.microsoft.com/#mscorlib/system/… shows that StringComparer.Ordinal uses String.Equals (rather than the other way around).Estrus

© 2022 - 2024 — McMap. All rights reserved.