- Home /
What does if (someComponent) statement return? Where would anyone use it?
Adding a null-check in my script, I mistyped this:
if (someComponent != null)
{
}
and ended up with something like:
if (someComponent)
{
}
Before correcting it, it made me wonder. What would this statement return anyway? Does it return something useful, meanningful? Does it check if "someComponent" exists? If it does, can it be used as an alternative to first piece of code that checks if someComponent is NOT valid?
This is not a Unity specific question but a more general C#-related one, and would be more usefull in a generic C# Q&A website.
After some research, I can't find any resources about a null check without the != null
"operand"
the two statements are, essentially, the same. It comes down to what means "false" and what means "true". Traditionally, false == 0, and true == anything else. Since null also means 0, your statement of
if(someComponent)
translates as
if(someComponent == true)
or
if(someComponent != false)
or
if(someComponent != null)
That being said, if I'm not mistaken, C# doesn't actually let you do that but something less hand-holdy would
Unity Object have the bool operator which automatically return a bool value when use a Component reference when a bool is needed.
See Object.bool.
Unity have other implicity conversions like Vector2 which can return Vector3 and Vector3 to Vector2, Color to Color32, Layer$$anonymous$$ask to int and many others.
you can create a implicit operator in this way:
public static implicit operator bool/*result type*/(Object/*original type*/ o)
{
return (null!=o);//return the converted type
}
Af far as I understand (and tested out), use of:
if (someComponent)
can be a substitute to:
if (someComponent != null)
But again, if I understand this all correctly, it only applies to ref types.