Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stringcomparison OrdinalIgnoreCase for true false values

Does this make sense? MyValue can be "true" or "false"

Should it not be Stringcomparison.OrdinalIgnoreCase ?

MyValue.Equals("true", StringComparison.CurrentCultureIgnoreCase))
like image 520
Pascal Avatar asked Mar 30 '12 12:03

Pascal


2 Answers

I would not do that. Just because a string is not equal to "true" does not mean it's equal to "false". This is an easy way to let ugly bugs slip in. I think you should parse the string

bool value;
if(!Boolean.TryParse(MyValue, out value)) {
    // it did not parse
}
// it parsed

This is more likely to be correct, and it's more readable. Plus, culture issues just got swept under the rug.

like image 127
jason Avatar answered Sep 21 '22 17:09

jason


It really depends on your situation and how the rest of your program is crafted. From the docs on OrdinalCompareCase

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames.

So basically, if the values are culture independent (generated progamatically, etc) use OrdinalIgnoreCase

like image 39
pstrjds Avatar answered Sep 18 '22 17:09

pstrjds