Possible unintended reference comparison

前端 未结 3 859
我寻月下人不归
我寻月下人不归 2020-11-28 16:15

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 \

相关标签:
3条回答
  • 2020-11-28 16:52

    Rebuild your project after you fix your code with this :

    if (lblStatus.Content.ToString() == "ACTIVE")
    if ((string)lblStatus.Content == "ACTIVE")
    if (lblStatus.Content === "ACTIVE")
    
    0 讨论(0)
  • 2020-11-28 17:07

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

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

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

    0 讨论(0)
  • 2020-11-28 17:14

    The warning is because the compile-time type of lblStatus.Content is object. 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:

    if (lblStatus.Content.ToString() == "ACTIVE")
    if ((string)lblStatus.Content == "ACTIVE")
    

    Note that the first of these will throw an exception if lblStatus.Content is 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.

    0 讨论(0)
提交回复
热议问题