Why if statements in Unity3d C # allow objects that are not bools?

In the standard .NET 4.6 compiler, the following if statement is not legal; you will receive a compiler error: CS0029 It is not possible to implicitly convert the type 'UserQuery.TestClass' to 'bool'. This is good and good, and I understand that.

void Main()
{
    TestClass foo = new TestClass();

    if(foo) 
    {
        "Huh. Who knew?".Dump();
    }
}


public class TestClass : Object
{
}

However, in Unity3d, this code is completely legal, and I have seen several examples that even encourage this zero-validation Javascript style.

What is going on here and is it possible to use this in my work, other than Unity3d, in .NET?

Here is an example of legal code in Unity3D:

using UnityEngine;

public class SampleIfBehavior : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {
        var obj = new SampleIfBehavior();

        if (obj)
        {
            Console.Write("It wasn't null.");
        }
    }
}

The plot is thickening! If I try to compare an object that is not the result of exclusive behavior, I get the expected compiler warning.

public class TestClass
{
}
void Start ()
{
    var obj2 = new TestClass();
    if (obj2) // cast from TestClass to bool compiler error
    {

    }
}

Unity3D ( , , .NET.)

( UnityEngine.Object):

public static implicit operator bool(Object exists)
{
  return !Object.CompareBaseObjects(exists, (Object) null);
}

public static bool operator ==(Object x, Object y)
{
  return Object.CompareBaseObjects(x, y);
}

public static bool operator !=(Object x, Object y)
{
  return !Object.CompareBaseObjects(x, y);
}
+4
1

. if (obj) Unity, Unity . , MonoBehaviour UnityEngine.Object.

:

public static implicit operator bool($classname$ other){
    return other != null;
}

Unity , , Unity. .

, Null-Coalescing . , null.

+11

Source: https://habr.com/ru/post/1683199/


All Articles