Use the Reference Equals and is operators to see if MonoBehaviour is really null

1 minute read

PR: CADDi is looking for back-end engineers, front engineers, algorithm engineers, SREs, etc..

It is a well-known fact that the comparison between MonoBehaviour and null is special. This is due to the methods ʻObject.operator bool, ʻObject.operator ==, and ʻObject.operator! = Of the base class of MonoBehaviour, ʻUnityEngine.Object.

Since the comparison between ʻoperator bool and null gives the same result, there is almost no point in using ʻoperator == or ʻoperator! = When comparing with null`.

Object-bool –Unity Script Reference
Object-operator! = –Unity Script Reference
-Object-operator == –Unity Script Reference

For example, if the property set is doing something other than just assigning to keep the state always correct, you may want to check if the object is really null before assigning.

SomeType someField;
SomeType SomeProperty {
    get => someField;
    set {
        someField = value;
        SomeMethod();
    }
}

In such cases, you can use System.Object.ReferenceEquals to check if the object is really null.

void UpdateSomeProperty() {
    if (!System.Object.ReferenceEquals(null, SomeProperty) && !SomeProperty) {
        SomeProperty = null;
    }
}

System.Object.ReferenceEquals can be described more easily by replacing it with ʻis null or ʻis object.

void UpdateSomeProperty() {
    if (SomeProperty is object && !SomeProperty) {
        SomeProperty = null;
    }
}

Use ʻis null to confirm that it is null, and use ʻis object to confirm that it is not null.

-[Object.ReferenceEquals (Object, Object) Method (System) Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/api/system.object.referenceequals)
-[is –C # Reference Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is)
- [Expressions - C# language specification Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/csharp/language-reference/language-specification/expressions#the-is-operator)
-[Type test operators and cast expressions-C # reference Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast# is-operator)

You can still use ReferenceEquals for comparisons with anything other than null.

SomeType someField;
SomeType SomeProperty {
    get => someField;
    set {
        if (ReferenceEquals(lockTarget, value)) {
            return;
        }
        someField = value;
        SomeMethod();
    }
}

void UpdateSomeProperty() {
    if (!SomeProperty) {
        SomeProperty = null;
    }
}