Alex
Alex

Reputation: 970

Checking if nullable type object is null (passes check, when it shouldn't)

So I created a nullable class, say called Unit, the instance is created:

unit??=new Unit(pars)

I check if it's null:

Debug.Log("check" + unit==null);

returns False. I test if it's null:

if (unit==null) continue;

And it passes the test for some reason. What's going on here? Why is is False, but passes the test?

Upvotes: -1

Views: 60

Answers (1)

Zeeshan Tariq
Zeeshan Tariq

Reputation: 31

The issue in this line: Debug.Log("check" + unit==null);

You're not testing whether unit is null as you might think. Instead, due to operator precedence, this statement is being evaluated like this: Debug.Log(("check" + unit) == null);

Correct Way to Check for Null: If you want to check whether unit is null and log the result, you should explicitly use parentheses to ensure the comparison happens first:

Debug.Log("check " + (unit == null));

Always use parentheses when combining comparisons and concatenation in a debug log to avoid confusion: Debug.Log("Is unit null? " + (unit == null));

Upvotes: 1

Related Questions