Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Possible unintended reference comparison. Consider casting the X side expression to type Y

Discussion in 'Scripting' started by SparrowGS, Jan 8, 2019.

  1. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    I have this line in a mb that also implements someInterface
    Code (CSharp):
    1. if(someInteface != this)
    now, if I try to cast it i get an error when ever the reference to someInterface is from a different mb that implements it, the reason i didn't do this in the first place.

    why is the unity console bugging me about it?
    Am i missing something? that line have been there for months without an issue, i'm getting pretty sick of seeing this warning pop up whenever i recompile the code
     
    Last edited: Jan 8, 2019
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    I think it's because it is never "this" due to being interface. You need to cast it first to the type. Although, that might not work as well.

    Problem with != is the same as == for the interface. It is overriden by Unity's operator, but for the interfaces used == as reference comparison. So, you're comparing references only, which causes that warning.
     
    JoshuaMcKenzie likes this.
  3. I guess you want to do this instead?
    Code (CSharp):
    1. if (this is someInterface)
    If you want to check that this implements someInterface.
     
    xVergilx likes this.
  4. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    I see. (sorry for the delay, I don't remember being alerted about this)

    well, the code I have actually runs perfectly fine so I don't really feel like changing it, and I was actually wondering if there's a way to tell unity to stop showing a warning in general.
     
  5. Charlicopter

    Charlicopter

    Joined:
    May 15, 2017
    Posts:
    125
    Ctrl+. => Suppress CS0252
     
  6. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    This warning is coming from C#. This comparsion will return true if someInterface refereces this, but if there's any comparsion operation defined on that classes, it won't be called. This warning warns you about this.