Updated:Those code was written in Unity, and Unity has overrided "==" operator and even the 'null'. That's the background.


enter image description here

Text version:

    var mirr = RecursedManager.instance.currentEntrance;

    if (mirr == null)
    {
        if (mirr is BoxExit)
        {
            var a = 1;// Even without debug mode, this line will be executed, if I use "print(1)" instead.

        }


    }

The image above is a screenshot taken while debugging in C#. It shows the execution reaching the line 'var a = 1'. Since it has reached this line, it indicates that both conditions 'mirr == null' and 'mirr is BoxExit' are true simultaneously. I don't understand why a null value can be judged as a subclass of the 'BoxExit' class.

I've heard an explanation that "variables contain type information, whereas null does not." This conclusion was also my initial reaction. However, I provided a simple example that seems to contradict this reasoning. For instance:

string aa = null;
bool b = aa is string;
print(b); // The output of b is false

Finally, some additional information (regarding the definition of 'currentEntrance', unsure if it's needed):

public IEntrance currentEntrance { get => _instance._currentEntrance; set => _instance._currentEntrance = value; }


private IEntrance _currentEntrance;

Where 'BoxExit' is a custom class I've defined, inheriting from Unity's 'MonoBehaviour' class. Additionally, the 'BoxExit' class implements the 'IEntrance' interface.

1

There are 1 best solutions below

0
Heinzi On BEST ANSWER

We don't know anything about the type of mirr, so we can only guess, but it's certainly possible for C# classes to override the == operator.

The following example (fiddle) will output True twice:

using System;

S s = new S();
Console.WriteLine(s == null);
Console.WriteLine(s is S);

class S
{
    public static bool operator==(S s1, S s2) => true;
    public static bool operator!=(S s1, S s2) => false;
}