Delegate.Target null-check fails when it's actually null and also prints as null.

I tried to make my example as concise as possible, but it’s still a little long. Apologies.

I have a standard delegate pattern,
but sometimes the class instance the delegate belongs to may have been destroyed when i go to call the delegate.
So, i check myDelegate.Target == null, but the check always evaluates an not-equal. But if the delegate itself prints out the value of this, the result is “null”.
So, i started checking if myDelegate.Target.ToString() is the string “null”, and that check behaves as expected. What am i missing here ? Is this a C# weirdness or a Unity weirdness ?

Here’s a script demonstrating the issue.

using UnityEngine;
using System.Collections;

// The console output of this program is this:
//
// nullMethod1: False nullMethod2: False
// Calling in method 1
// You called me! this = New Game Object (LittleGuy)
// Calling in method 2
// You called me! this = New Game Object (LittleGuy)
// doing careful delegate callback after the GameObject the delegate belonged to has been destroyed..
// nullMethod1: False nullMethod2: True
// Calling in method 1
// You called me! this = null

public class LittleGuy : MonoBehaviour {
  public void callMe() {
    Debug.Log("You called me! this = " + this.ToString());
  }
}

public class delegateTargetTest : MonoBehaviour {

  public delegate void SimpleDelegate();

  public SimpleDelegate myDelegate;

  public void Start() {

    GameObject go = new GameObject();
    LittleGuy lg = go.AddComponent<LittleGuy>();
    StartCoroutine(beginTest(lg.callMe));

    GameObject.Destroy(go);
  }

  private IEnumerator beginTest(SimpleDelegate dtt) {
    Debug.Log("doing careful delegate callback while everything is fine..");
    tryCallDelegate(dtt);

    // give the GameObject time to be destroyed.
    yield return new WaitForSeconds(0.5f);

    Debug.Log("doing careful delegate callback after the GameObject the delegate belonged to has been destroyed..");
    tryCallDelegate(dtt);
  }

  void tryCallDelegate(SimpleDelegate dtt) {
    bool nullTestMethod1 = (dtt.Target == null);
    bool nullTestMethod2 = string.Equals(dtt.Target.ToString(), "null");
    Debug.Log("nullMethod1: " + nullTestMethod1 + " nullMethod2: " + nullTestMethod2);

    if (!nullTestMethod1) {
      Debug.Log("Calling in method 1");
      dtt();
    }

    if (!nullTestMethod2) {
      Debug.Log("Calling in method 2");
      dtt();
    }
  }
}

As you might know in the C# world it’s impossible to actually destroy any objects. Class instances are actually destroyed by the garbage collector once all references to the instance are gone. However all classes derived from UnityEngine.Object can be destroyed since they have a C++ counterpart in the engines core.

The managed “part” of those objects can’t be destroyed. References in the managed world are always valid unless they are actually null. Unity implemented a custom == operator for the UnityEngine.Object class which when comparing the instance to null will check if the object has been destroyed and return “true”, even the (managed) object is still there. They also implemented a custom Equals method which also returns “true” when comparing to null.

This works pretty well as long as you work with variable of type UnityEngine.Object or any derived type (like GameObject, Component, MonoBehaviour, …). However if you cast such a reference to System.Object the custom == operator isn’t used so a null check will return false since the actual managed object is still there.

If you want to do a null check of a System.Object reference and include Unity’s fake-null-objects you can do this:

object obj;

if (obj == null)
    return; // the reference actually is null --> early exit
if ((obj is UnityEngine.Object) && (obj.Equals(null)))
    return;  // the object is a fake-null object --> early exit
// now savely use "obj"

See this blog post for more details