Search Unity

Bug Calling .GetHashCode() on instances of empty structs doesn't return the same value in il2cpp builds

Discussion in 'Scripting' started by Nicolas-Vidal-Iscool, Mar 17, 2022.

  1. Nicolas-Vidal-Iscool

    Nicolas-Vidal-Iscool

    Joined:
    Mar 4, 2015
    Posts:
    6
    Hey there, I just encounter something that feels like a bug.

    Let's say we have an empty struct :

    Code (CSharp):
    1. public struct EmptyStruct
    2. {
    3. }
    If we create two instances of this struct and store them in two different variables :

    Code (CSharp):
    1. var emptyStruct1 = new EmptyStruct();
    2. var emptyStruct2 = new EmptyStruct();
    I would expect .Equals to be true between them and thus .GetHashCode() returning the same value :

    Code (CSharp):
    1. Debug.Log($"Are Empty StructGetHashCode the same ? {emptyStruct1.GetHashCode() == emptyStruct2.GetHashCode()}");
    2. Debug.Log($"Are EmptyStruct Equals ? {emptyStruct1.Equals(emptyStruct2)}");
    It turns out everything is fine in Editor and in Mono Build.

    Code (CSharp):
    1. Are EmptyStruct GetHashCode the same ? True
    2. Are EmptyStruct Equals ? True
    But ..

    When I build the project with IL2CPP, .Equals() still is true, but their .GetHashCode() returns different values, which seems contradictory to the classic Equals/GetHashCode usage.

    Code (CSharp):
    1. Are EmptyStruct GetHashCode the same ? False
    2. Are EmptyStruct Equals ? True
    This behaviour is observed in Unity 2020.3.28f1 and also Unity 2021.2.15f1 on Android IL2CPP builds (and I think in all IL2CPP builds).

    Ugly ways to 'fix' this involve overriding .GetHashCode() in the empty struct or just adding an unused field.

    Is there something I miss ?

    Just in case I created a bug report (https://fogbugz.unity3d.com/default.asp?1411455_rs5538034dq74a9l) and a colleague of mine recommended me to tag @JoshPeterson

    Thank you all for your insights :)
     
  2. Nicolas-Vidal-Iscool

    Nicolas-Vidal-Iscool

    Joined:
    Mar 4, 2015
    Posts:
    6
  3. JoshPeterson

    JoshPeterson

    Unity Technologies

    Joined:
    Jul 21, 2014
    Posts:
    6,936
    We've corrected this issue internally - you should be notified via the bug report about it soon.
     
    Nicolas-Vidal-Iscool likes this.