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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.