'Possible unintended reference comparison

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?



Solution 1:[1]

I prefer to stick to the string.Equals(string,string,StringComparison) method, like this:

string contentStr = (lblStatus.Content ?? string.Empty).ToString();
if (string.Equals("ACTIVE", contentStr, StringComparison.OrdinalIgnoreCase))
{ 
    // stuff
} 

because it explicitly states what it does + it doesn't give a warning you've mentioned.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pang