简体   繁体   中英

Can a C# object be 'null' but still have properties?

I have an object for which I can print its properties (like 'name', 'id',...) in a debug console. On the very next line, I print the object itself, and there I get 'null'. Kind of like this:

Debug.Log($"Item name is {item.name}");
Debug.Log($"Item is {item}");
if (item == null)
{
    Debug.Log("Yes, item is null!");
}

So the first line will print a correct name, the second prints 'null'. The third line prints "Yes, item is null!".

How is that possible? (I don't know if this is relevant, but this happens in a code for Unity.)

Thank you, Arnaud.

That's because UnityEngine.Object overload == , != and bool operators.

https://docs.unity3d.com/ScriptReference/Object-operator_eq.html

A Unity object will equal to null after it is destroyed, but you can still access part of its properties.

You can use the following condition to check whether a Unity object is completely null or not.

(object)item == null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM