I wonder if I must define a commutative operator (like *
) twice!
public static MyClass operator *(int i, MyClass m)
{
return new MyClass(i *
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.
Order is sometimes important in operators, the classic examples being subraction (-
) and division (/
). However, it can also apply to multiplication:
Consider, for example, that they are vectors - x
is a (2×1) vector, and y
is a (1×2) vector. If we interpret *
as matrix multiplication, then x * y
is a (2×2) vector, but y * x
is a (1×1) vector.
As such, the C# compiler does not assume that binary operators are commutative, even if they commonly are (addition (+
), multiplication (*
), etc).
You don't have to do that - you only need to do that if you want to be able to write:
MyClass x = ...;
MyClass y = x * 5;
MyClass z = 5 * x;
If you only want one of the bottom two lines to be valid, you can delete the other operator overload.
Basically, the C# language doesn't assume that multiplication is commutative even in terms of the types involved.
class MyClass {
private int i;
public MyClass(int x) {
i=x;
}
public static MyClass operator+(MyClass a , MyClass b) {
return new MyClass(a.i+b.i);
}
public static implicit operator MyClass(int a) {
return new MyClass(a);
}
static void Main(string[] args) {
MyClass a , b ,c ;
a=new MyClass(2);
b=a+4;
c=4+a;
Console.WriteLine("B = {0}, C = {1}",b,c);
}
There you go, all you have to do is have the compiler turn int into MyClass instance and then use the MyClass + MyClass method.