Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must I define a commutative operator twice?

Tags:

c#

I wonder if I must define a commutative operator (like *) twice!

public static MyClass operator *(int i, MyClass m)
{
    return new MyClass(i * m.Value);
}

public static MyClass operator *(MyClass m, int i)
{
    return new MyClass(m.Value * i);
}

What's the logic behind this?


Additional Descriptions: Dear @Marc's answer about Vector and Matrix multiplication was good if and only if we assume operand types are different !!! It's evident that we can define * operator only once to perform Vector or Matrix multiplication. So I think this is not the answer.

@Marc: Order is sometimes important in operators.

Yes, but this is not equivalent with Order is sometimes important in operands! The above sentence may be used in case of using + operator before (or after) * operator that it will cause to different results. For example:

0 + 2 * 2 != 0 * 2 + 2

Assume that we've defined * operator as:

public static MyClass operator *(MyClass m1, MyClass m2)
{
    return new MyClass(m1.Value * m2.Value /* or some other kind of multiplication */);
}

We can not define it again.

public static MyClass operator *(MyClass m2, MyClass m1) { ... }

If so, compiler would tell us that type MyClass already defines a member called 'op_Multiply' with the same parameter types.

Now, we can use this operator in two ways: m1 * m2 or m2 * m1 and they may have different results which depend on multiplication procedure.

like image 496
Mehdi Avatar asked Sep 12 '11 09:09

Mehdi


1 Answers

For commutative operations, you don't need to implement the entire thing twice, you can reference the initial operator. For example:

    public static Point operator *(Point p, float scalar)
    {
        return new Point(
                scalar * p.mTuple[0],
                scalar * p.mTuple[1],
                scalar * p.mTuple[2]
            );
    }

    public static Point operator *(float scalar, Point p)
    {
        return p * scalar;
    }

I hope that this helps.

like image 195
Gary Paluk Avatar answered Sep 23 '22 03:09

Gary Paluk