patterncsharpModerate
Comparison between strings
Viewed 0 times
betweenstringscomparison
Problem
This review is very short and very straight-forward. There are two people in the team and the checked-in code looks as follows.
I got stuck here and needed to re-check the usage of CompareTo. I can't for my life understand any advantage of the above in comparison to:
I'm pretty sure it's just a case of intentional obfuscation or, at the very least, lack of understanding a copied code.
Is the former inferior to the latter in every possible way?
The author of the first claims that since both work, they're comparably good and the difference is just a matter of personal taste.
string parameter = GetUnitType();
string target = "PM4000";
if(parameter.CompareTo(target) == 0)
CarryOutProcess();I got stuck here and needed to re-check the usage of CompareTo. I can't for my life understand any advantage of the above in comparison to:
string parameter = GetUnitType();
if(parameter == "PM4000")
CarryOutProcess();I'm pretty sure it's just a case of intentional obfuscation or, at the very least, lack of understanding a copied code.
Is the former inferior to the latter in every possible way?
The author of the first claims that since both work, they're comparably good and the difference is just a matter of personal taste.
Solution
There is a subtle difference between
However, as Ben points out in the comments, the official recommendation is to use
Your devs might also be coming from a Java background where
== and CompareTo: the latter is current-culture-aware (or you can pass another one in), the former is not.However, as Ben points out in the comments, the official recommendation is to use
Equals instead of CompareTo outside of sorting operations.Your devs might also be coming from a Java background where
== and equals are a bit more complicated and may very well produce different results. This isn't a concern in C#, so for the vast, vast majority of your equality checks the == will be more than sufficient.Context
StackExchange Code Review Q#63805, answer score: 16
Revisions (0)
No revisions yet.