2

Unity has a struct Color. It's default value is Color.white. So to check if it is its default value, I can use myColor == default(Color) or myColor == Color.white.

However, I came across some code that checks if myColor == null. The code compiles, and Visual Studio gives the suggestion to turn it into false. I assume this is because a Color cannot be null. This applies to all Unity structs I have seen, such as Vectors as well.

If I use a regular struct in C#, it gives me the suggestion, but also fails to compile.

Color myColor = new Color();
bool defaultColor = myColor == null; //Compiles

MyStruct myStruct = new MyStruct();
bool defaultStruct = myStruct == null; //Does not compile

Why do Unity Structs allow null checks? Why does this compile?

Evorlor
  • 7,263
  • 17
  • 70
  • 141
  • 6
    To paraphrase the duplicate's answer, because the `Color` type has a overloaded `==` operator, the compiler "lifts" an overloaded `==` operator for `Nullalbe`, lifts both the `Color` and the null literal to `Nullable` and uses that operator. – D Stanley Aug 27 '18 at 14:25
  • Whoever deleted their answer, why? That was a useful answer specific to my case, showing why it was a duplicate. The reference to the source code also helped: https://github.com/Unity-Technologies/UnityCsReference/blob/54dd67f09e090b1ad5ba1f55886f327106406b0c/Runtime/Export/Color.cs#L95 – Evorlor Aug 27 '18 at 14:29
  • It compiles because the struc Color overloads the == operator. The same thing happens with the DateTime struct. If you overload the == and != operators in MyStruct, it will compile – J.Loscos Aug 27 '18 at 14:30
  • 1
    Also see Eric Lippert's comment to his accepted answer to the marked duplicate question: *"User-defined value types which have a user-defined equality operator defined also by default have a lifted user-defined equality operator generated for them. The lifted user-defined equality operator is applicable for the reason you state: all value types are implicitly convertible to their corresponding nullable type, as is the null literal. It is not the case that a user-defined value type that lacks a user-defined comparison operator is comparable to the null literal."* – Rufus L Aug 27 '18 at 14:34
  • 1
    @Evorlor I think it was deleted because it did not fully answer the question and because a duplicate was found. I have voted to undelete it because it does give the reason that the duplicate answer applies. – D Stanley Aug 27 '18 at 15:13
  • Structs cannot be nullable, instead you can remplace struct by class which is nullable. – GhAyoub Aug 27 '18 at 19:09

0 Answers0