Comparing two strings, ignoring case in C#
If you're looking for efficiency, use this:
string.Equals(val, "astringvalue", StringComparison.OrdinalIgnoreCase)
Ordinal comparisons can be significantly faster than culture-aware comparisons.
ToLowerCase
can be the better option if you're doing a lot of comparisons against the same string, however.
As with any performance optimization: measure it, then decide!
The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.
The .ToLowerCase
version is not going to be faster - it involves an extra string allocation
(which must later be collected), etc.
Personally, I'd use
string.Equals(val, "astringvalue", StringComparison.OrdinalIgnoreCase)
this avoids all the issues of culture-sensitive strings, but as a consequence it avoids all the issues of culture-sensitive strings. Only you know whether that is OK in your context.
Using the string.Equals
static method avoids any issues with val
being null
.