String comparison article does not explain the correctness of using 'is' to compare strings. #42548
Description
Type of issue
Missing information
Description
So the https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is
is pattern operator was added to the language spec, and has a variety of interesting supported behaviors. You can use it with string literals.
Now, I'll admit I didn't read up on pattern matching, so I've thought for a while now that
E is C (some constant expression) were value level comparisons. EG,
if (myObj.Iterations is 0) would be a struct-level raw-byte equality check.
As such I've seen developers using if (myObj.MyStringProperty is "someStringConstant") ...
and assumed that this would only evaluate to true for interned strings, as I expected this was a pointer-level-equality (the struct of the reference, in my head) and interned strings are pointer equal even when they came from different sources so in my head, this is why the string is constant code worked. So I've had a suspicion for a while now that if you built a string in a weird way https://medium.com/@anupsarkar-dev/string-interning-in-c-47608faf6f8f#:~:text=It%20is%20important%20to%20note,you%20explicitly%20use%20the%20string.
this is would evaluate to false for strings where == would evaluate to true.
Now that I figured out that this 'struct constant' is
is the same as the pattern matching is
(I thought they were different, it isn't inherently obvious that 'constants' would be valid patterns, intuitively) and read up on the pattern matching docs, I can see strings are explicitly supported so all of this code is safe. However, it was a slog to find ANY information on this topic, going through all the string comparison docs, stackoverflow questions on string comparisons, .NET docs, etc all came up dry.
Given that, it seems like it would be good for the official "string comparison methods" article to mention this new is
pattern matching mechanism for checking strings against string literals, explicitly declaring it safe for those of us who haven't deep dove the pattern matching spec, and perhaps mentioning whether it has any performance implications (is is
faster than == string literal? etc).
Thanks!
Page URL
https://learn.microsoft.com/en-us/dotnet/csharp/how-to/compare-strings
Content source URL
https://github.com/dotnet/docs/blob/main/docs/csharp/how-to/compare-strings.md
Document Version Independent Id
82f53ae8-a9d4-dea9-5acd-6d9202a40882
Article author
Metadata
- ID: 11ecfc18-477b-f792-4136-2feb46bbc5d3
- Service: dotnet-csharp
- Sub-service: fundamentals