✅ I'm having trouble understanding what is going on within this selection search
I'm mostly confused about the if statement. What is happening there?
13 Replies
It seems to be comparing two strings, I think I understand that much. I'm not sure what the true is, and what is the purpose of the <0? Strings aren't values are they?
At a quick glance, It's comparing strings for their lexical ordering...this is how you sort strings. A given string is either "less than" another string in the sort order, "greater than" in the sort order, or equal.
-1 means less than, 0 means equal, 1 means greater than
ty
I need to find more to read about this, because I still don't have a strong grasp on it
Imagine a dictionary of English words, like Webster's dictionary or similar. The words are sorted from the first page to the last, right? Well if you had to do that in code, the string comparison mechanism implements the logic to determine if one word should appear before or after another...
Ah okay
That makes sense
I'm going to try debugging it tomorrow and watching for the values to change. The -1, 0, and 1
And I'll keep that concept in mind
The "true" in the string.Compare call is documented here:
https://learn.microsoft.com/en-us/dotnet/api/system.string.compare?view=net-7.0#system-string-compare(system-string-system-string-system-boolean)
String.Compare Method (System)
Compares two specified String objects and returns an integer that indicates their relative position in the sort order.
It means "do a case insensitive compare"
strictly speaking, the function doesn't guarantee that the result will be -1, 0 or 1, instead of being -1 it could be -2 or less, and vice versa so you should check against 0 always
> 0, < 0, == 0
That's a good point.
In what instance would it be -2?
It depends on how the comparer is implemented. As far as I know the default string comparer only ever uses -1, 0 and 1, but the documentation is that a value less than zero is returned, zero is returned, or a value greater than zero is returned...so strictly speaking someone could change the implementation of the compare to use other values...
ty
Closed!