Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

C#'s ??-Operator in Unity

Discussion in 'Scripting' started by lactus, Sep 10, 2014.

  1. lactus

    lactus

    Joined:
    Oct 20, 2013
    Posts:
    6
    Hi folks,

    can anyone explain me the diffrence between this two code segments?
    They should do the same, but somehow the ??-Operator fails

    Code (CSharp):
    1. public InventarItem(InventarItem _original)
    2. {
    3. m_ID = _original.m_ID;
    4. m_Name = _original.m_Name;
    5. m_Picture = _original.m_Picture ?? InventarController.Instance.m_DefaultPicture; // does not work if _original.m_Picture is null
    6. }
    7. public InventarItem(InventarItem _original)
    8. {
    9. m_ID = _original.m_ID;
    10. m_Name = _original.m_Name;
    11. m_Picture = _original.m_Picture != null ? _original.m_Picture : InventarController.Instance.m_DefaultPicture; // works
    12. }
     
    Last edited: Sep 10, 2014
  2. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    868
    Unity has overridden the == operator to return things as null, even when they're not, and vice versa.
    http://docs.unity3d.com/ScriptReference/Object-operator_eq.html

    When you call Destroy(gameObject), the gameObject is not instantly removed from memory - it's kept around in a "destroyed" state. Unity's == override takes this into account, so if you compare a "destroyed" state gameObject to null with ==, it works as you'd expect. But, the null coalescing operator (??) doesn't have a clue what's going on, so it sees the object and returns it as non-null.

    Sucky, but that's why.
     
  3. lactus

    lactus

    Joined:
    Oct 20, 2013
    Posts:
    6
    Ok, thank you, this makes a lot of sense...

    So the null coalescing operator won't work with any classes provided by unity?
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Nothing that derives from UnityEngine.Object
     
  5. GarthSmith

    GarthSmith

    Joined:
    Apr 26, 2012
    Posts:
    1,240
    Is there a reason for overloading == and not ??, or is overloading ?? something we should request from Unity?
     
  6. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    AFAIK you actually can't overload the coalescing operator.
     
  7. flaminghairball

    flaminghairball

    Joined:
    Jun 12, 2008
    Posts:
    868
    C# doesn't allow ?? overrides - just ==.