2.16. Operator Overloading

Operator overloading allows us to provide class-specific instances of the existing operators, such as addition, multiplication, equality, and so on. For example, rather than providing a named function, such as multiplyByDouble(), for a Matrix class, we can overload the multiply operator to perform the same task. That is, rather than writing

Matrix newMat = Matrix.multiplyByDouble( mat, dval );

the user can write the more intuitive

Matrix newMat = mat * dval;

Here is how we might implement this instance of the multiply operator:

 public class Matrix { public static Matrix operator*(Matrix mat, double dval) { Matrix result = new Matrix( mat.rows, mat.cols ); for ( int ix = 0; ix < mat.rows; ix++ ) for ( int iy = 0; ...

Get C# Primer: A Practical Approach now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.