Is there a difference in the order of equality?

Or, in short, do you need a second operator?

    public static bool operator ==(Vector3 v, float scalar)
    {
        return v.X == scalar && v.Y == scalar && v.Z == scalar;
    }

    public static bool operator ==(float scalar, Vector3 v)
    {
        return v == scalar;
    }
+3
source share
2 answers

Yes, this is necessary if you want to allow asymmetric equality tests:

bool foo = (yourVector3 == 5);    // requires the first version
bool bar = (5 == yourVector3);    // requires the second version

Without the first version, you will get a compile-time error saying something like "Operator" == 'cannot be applied to operands like "Vector3" and "int". Without the second version, the error will say something like "Operator" == 'cannot be applied to operands like "int" and "Vector3".

+4
source

, , . a == b, b == a . - , , , , .

'==' "float" "Vector3"

, , . .

+2

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


All Articles