Reputation: 321
I read from a text file . in that text file a line is with YES or NO (yes if it's correct, no if it's not)
I used at the beginning answer.Tag = "NO;"
then when I press a button it goes answer.Tag = "YES";
I have a verify button which does
if (answer[0].Tag == "bla bla" && answer[1].Tag== "blabla2")
{
MessageBox.Show("They Match");
}
else
MessageBox.Show("They don't");
Then I have this problem : Warning 1 Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
I don't know why it doesn't do the comparison . It skips to else
Upvotes: 1
Views: 11413
Reputation: 23300
The Possible unintended reference comparison
is this one:
answer[1].Tag == "blabla2"
The Tag
is an object
, you are allowed to compare it to "blabla2"
because string
is a reference type. The compiler is "casting" your string
to object
and is performing a reference comparison (which will evaluate to false
since they are not the same object).
To fix this, you have to cast Tag
before checking. Together with the fix I mentioned above, your code would become
if (answer[0].Tag.ToString() == "bla bla" && answer[1].Tag.ToString() == "blabla2")
{
MessageBox.Show("They Match");
}
else
MessageBox.Show("They don't");
Upvotes: 4
Reputation: 73492
Usually Tag
property will be of type Object
, so I assume it is of type Object
. ==
operator with System.Object
work as reference comparison (meaning references of the instances are compared than value).
To fix it just introduce a cast to string.
if ((string)answer[0].Tag == "bla bla" && (string)answer[1].Tag== "blabla2")
{
MessageBox.Show("They Match");
}
else
{
MessageBox.Show("They don't");
}
Upvotes: 0
Reputation: 5822
correction of your code:
if (answer[0].Tag == "bla bla" && answer[1].Tag== "blabla2")
{
MessageBox.Show("They Match");
}
else
MessageBox.Show("They don't");
here specifically in your if condition:
if (answer[0].Tag **==** "bla bla" && answer[1].Tag== "blabla2")
should be 2 equals signs, not one
Upvotes: 0