Thursday, June 28, 2007

Beware of "==" in VC++

"==" operator of String class may not return desired result. For example, when checking the equality of two Strings:

if (cmbBx_Pos->Text == S"BOL")

Even if the two Strings are the same, it may have a "false" result. To make sure it return the correct result, use this instead:

if (cmbBx_Pos->Text->Equals(S"BOL"))

It doesn't make much sense why the "==" operator failed. Perhaps it was the operator of Object class, so it was comparing two references instead of two Strings.

Updated: when using a .net string literal in VC, always write as: S"hello". "==" operator will return false when comparing "hello" and S"hello". If a project has only .net strings as S"xxx", using "==" operator probably has no problem. If a project deals with different kinds of string, we better off use String::Equals to check string equality.

No comments: