- Home /
Why does monobehavior in if statement compiles?
Hi,
I've noticed something odd when using MonoBehavior variables alone in an if statement: The fact that is compiles.
What I'm talking about is this,
if(monobehaviorDerivedObject){
}
or even this,
if((new Monobehavior()){
}
will compile!
Now this looks a lot like the C++ syntax for determining if a pointer is == null, but I doubt this is the same thing. Using a standard C# class (inheriting from System.Object) won't compile because the object cannot be converted to bool..
So my question is.. If Monobehaviors can be converted to bool, what is the meaning of the resulting conversion, and how is this achieved (I haven't seen any ToBool() function)?
Answer by elenzil · Apr 27, 2017 at 11:21 PM
interesting!
it looks like it's this, down in UnityEngine.Object:
public static implicit operator bool (Object exists);
( MonoBehaviour > Behaviour > Component > Object )
Thanks! It looks like I was not far with the C++ syntax. I didn't know that "public static implicit operator bool()" was possible. That's really good to know!
It's a casting operator to bool. A class can implement arbitrary casting operators. Those operators can be implicit or explicit. An explicit casting operator would require an explicit cast into that type.
Example:
public class Test
{
public string str;
public static implicit operator Test(int someValue)
{
return new Test { str = "value: " + someValue };
}
public static implicit operator int(Test aObj)
{
if (aObj == null)
return 0;
return aObj.str.Length;
}
public static explicit operator string(Test aObj)
{
if (aObj == null)
return "";
return aObj.str;
}
}
This class allows the following:
Test obj = 5; // creates Test object with str set to "value: 5"
int len = obj; // returns the length of the str variable
string s = obj; // error, no implicit cast to string
string s2 = (string)obj; // works
string s3 = (string)(Test)42; // works as well
You should only implement implicit casts which naturally makes sense (which they don't in my example ^^).
this is a great write-up.
personally, i'm of the camp that never uses implicit operators, even in my vector libraries. ie, i think it's better to have "v1.add(v2, v3)" than "v3 = v1 + v2". my reasoning is that the implicit operators are so easy to glance over that it's also easy to overlook the fact that really they could be doing anything, from a logical & performance point of view.
btw, i just realized that you wrote SimpleJSON. that's awesome. we're still using it even tho unity has one also now. last week i extended it to include ".AsLong".
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to change the values of an animation using a variable ??? 2 Answers
Distribute terrain in zones 3 Answers
Some Boolean "Action" Trouble 2 Answers