I have the following code which gives a warning
Possible unintended reference comparison; to get a value comparison, cast the left hand side to type ‘string’`
if (lblStatus.Content == "ACTIVE")
{
//Do stuff
}
else
{
//Do other Stuff
}
I’m assuming the warning is because lblStatus.Content may not necessarily always be of type string?
I’ve tried to fix it using each of the following but I still get a warning
if (lblStatus.Content.ToString() == "ACTIVE")
if ((string)lblStatus.Content == "ACTIVE")
if (lblStatus.Content === "ACTIVE")
Please could someone explain the reason I still get a warning and the best practical way to deal with this?
The warning is because the compile-time type of
lblStatus.Contentisobject. Therefore operator overloading chooses the==(object, object)overload which is just a reference identity comparison. This has nothing to do with what the execution-time type of the value is.The first or second of your options should have fixed the warning though:
Note that the first of these will throw an exception if
lblStatus.Contentis null. I would prefer the second form.If you think you’re still seeing a warning at that point, I suspect you either haven’t rebuilt – or something is still “dirty” in your build. A full rebuild absolutely should remove the warning.