O'Reilly logo

C# Primer: A Practical Approach by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required