I don’t know the correct terminology to explain what I am trying to do, but in C# you can check if an object is null by using the following:
if (<object>)
{
Debug.Log("it is not null");
}
else
{
Debug.Log("the object is null");
}
but when I try to do this using my own classes, i get the error
“Cannot convert object to bool”
I want to do this:
public class Foo
{
//...
}
Foo foo = new Foo();
if (foo)
{
//...
}
But this generates the above error message.
So how can you define this operation in your class?
Is there an overloaded operator to define?
Thanks.
1 Like
system
July 31, 2015, 5:06pm
2
if (myObject == null)
// do stuff
1 Like
I realize you can do it that way,
but is there a way just do this:
if ( ! myObject)
{
}
I’m interested in how to do that in C#.
OwenG
July 31, 2015, 5:18pm
5
You can override the == operator for your class and do a reference equivalence check inside. See this StackOverflow answer for code example: c# - Overriding == operator. How to compare to null? - Stack Overflow
Personally, I like doing (if myObj == null), because it makes the code explicitly clear about what’s going on.
Owen
1 Like
Ok thanks. i started to suspect you couldn’t because i couldnt find any examples using it. I wonder how the C# compiler is able to do it using UnityEngine.GameObject
you can do this:
UnityEngine.GameObject myUnityEngineObject;
if (myUnityEngineObject)
{
}
So i wonder how it can handle that, but not your own defined class.
system
July 31, 2015, 5:37pm
7
OwenG:
You can override the == operator for your class and do a reference equivalence check inside. See this StackOverflow answer for code example: http://stackoverflow.com/a/4219274
Personally, I like doing (if myObj == null), because it makes the code explicitly clear about what’s going on.
Owen
That’s different from what the OP is talking about.
ArachnidAnimal:
Ok thanks. i started to suspect you couldn’t because i couldnt find any examples using it. I wonder how the C# compiler is able to do it using UnityEngine.GameObject
you can do this:
UnityEngine.GameObject myUnityEngineObject;
if (myUnityEngineObject)
{
}
So i wonder how it can handle that, but not your own defined class.
I can’t test whether this works or not but if it works it would be due to implicit conversation from GameObject to bool. You could do the same if you wanted to although it would probably be more hassle to implement it than to check using the way I showed you.
https://msdn.microsoft.com/en-us/library/z5z9kes2.aspx
1 Like
OK, THANKS!
That was exactly what I was hoping for. It works now when I defined the following in my class:
public static implicit operator bool (MyObject myObject)
{
return (myObject != null);
}
now i can do the null check by the following:
if (myObject)
{
//...
}
2 Likes