Marek
Marek

Reputation: 3575

Possible unintended reference comparison issue

May I ask what it might cause when I didn't fix this?

Second question is what is the possibility to fix it.

I'm receiving it with following code:

if (cb_vyber_cena.SelectedItem == "Jiná"){ cena_zaj = txt_jin_cena.Text;} 

I get following warning:

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'

Upvotes: 2

Views: 3289

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063433

== is overloaded as a static operation, not as a virtual operation. If SelectedItem is typed as object, this will only ever perform a reference equality check. If you intend to compare the values as strings, you need to add a cast:

if ((string)cb_vyber_cena.SelectedItem == "Jiná") {
    cena_zaj = txt_jin_cena.Text;
} 

This will allow it to use the == overloaded by the string type. Note that if you aren't sure that SelectedItem is a string you might need a type test too:

if ((cb_vyber_cena.SelectedItem as string) == "Jiná") {
    cena_zaj = txt_jin_cena.Text;
} 

Alternatively, you could use the virtual implementation of Equals:

if ("Jiná".Equals(cb_vyber_cena.SelectedItem)) {
    cena_zaj = txt_jin_cena.Text;
} 

Noting that I used "Jiná" on the left hand side to avoid issues if SelectedItem is null.

Upvotes: 8

Related Questions