Odd variable behaviour inside constructor

// public ThisClass(..., ..., ..., ..., List<MyStruct> thisItem, ...) {

Log("Type: " + thisItem.GetType());
// "Object reference not set to an instance of an object"

Log("Item: " + thisItem);
// "Item: "

Log("Count:" + thisItem.Count);
// "Object reference not set to an instance of an object"

Log("IsNull:" + thisItem == null);
// IDE: "Expression is always false", I confirmed it later, it indeed returns "false".

this.thisItem = thisItem.Count == 0 || thisItem == null ? thisItem : new List<MyStruct>();
// "Object reference not set to an instance of an object"

Log($"{this.thisItem}");
// Won't invoke, throws before that

Errors are inside comments. Replacing Log with Debug.Log doesn’t change anything.

Is this used as a static or member variable, and does thisItem point to a UnityEngine.Object type?

Those calls happen NOT on the Unity main thread.

ie.,

private Foo foo = new Foo();

The contents of the constructor are NOT run by the Unity main thread but by a loader thread, if the above code is in a MonoBehavior. This means you can’t access most stuff in Unity. Instead, do the ctor call in Awake().

If the IDE is warning “expression is always false”, then this isn’t just a Unity-ism; you have somehow structured your code in a way that a variable you think should have a valid value is guaranteed not to, by static analysis. You probably have a mistake in some code that you didn’t post.

Are you sure, or is it misleading due to rules about order of operation?

We’re thinking this:

"IsNull:" + (thisItem == null).ToString()

But what is happening is:

("IsNull:" + thisItem.ToString()) == null

Addition of string happens before comparison happens, can static analysis be seeing “Well it’s a string literal, nothing you can add to that can make it a null?”

https://www.tutorialspoint.com/csharp/csharp_operators_precedence.htm

3 Likes