This example is modified from msdn, is also an example of 'indexers", that resembles properties that can take parameter. |
using System; // csc use_this_operator.cs class Cube { // its a 3D matrix public const int dimtype = 3; private double[,] matrix = new double[dimtype, dimtype]; // allow callers to initialize public double this[int x, int y] { get { return matrix[x, y]; } set { matrix[x, y] = value; } } // let user add matrices public static Cube operator +(Cube mat1, Cube mat2) { Cube newMatrix = new Cube(); for (int x=0; x < dimtype; x++) for (int y=0; y < dimtype; y++) newMatrix[x, y] = mat1[x, y] + mat2[x, y]; return newMatrix; } } class MatrixTest { // used in the IntCube method. public static Random rand = new Random(); // test Cube static void Main() { Cube mat1 = new Cube(); Cube mat2 = new Cube(); // init matrices with random values IntCube(mat1); IntCube(mat2); // print out matrices Console.WriteLine("Matrix 1: "); PrintCube(mat1); Console.WriteLine("Matrix 2: "); PrintCube(mat2); // perform operation and print out results Cube mat3 = mat1 + mat2; Console.WriteLine(); Console.WriteLine("Matrix 1 + Matrix 2 = "); PrintCube(mat3); } // initialize matrix with random values public static void IntCube(Cube mat) { for (int x=0; x < Cube.dimtype; x++) for (int y=0; y < Cube.dimtype; y++) mat[x, y] = rand.NextDouble(); } // print matrix to console public static void PrintCube(Cube mat) { Console.WriteLine(); for (int x=0; x < Cube.dimtype; x++) { Console.Write("[ "); for (int y=0; y < Cube.dimtype; y++) { // format the output Console.Write("{0,8:#.000000}", mat[x, y]); if ((y+1 % 2) < 3) Console.Write(", "); } Console.WriteLine(" ]"); } Console.WriteLine(); } } |