Monday 25 February 2013

Example of Operator Overloading


// Add a new class Matrix.cs
using System;
namespace CSharpConsole
{
    class Matrix
    {

        //declaring variables for a 2*2 matrix
        int a, b, c, d;
        public Matrix(int a, int b, int c, int d)
        {
            //initializing the matrix varaibles
            this.a=a ; this.b=b ;
            this.c=c ; this.d=d ;
        }

        // overloading the + operator so that it can be used for adding values of 2 matrix
        public static Matrix operator + (Matrix m1, Matrix m2)
        {
            Matrix obj = new Matrix(m1.a + m2.a, m1.b + m2.b, m1.c + m2.c, m1.d + m2.d);
            return obj;
        }

        // overloading the - operator so that it can be used for substracting values of 2 matrix
        public static Matrix operator -(Matrix m1, Matrix m2)
        {
            Matrix obj = new Matrix(m1.a - m2.a, m1.b - m2.b, m1.c - m2.c, m1.d - m2.d);
            return obj;
        }

        //overriding the ToString method inherited from object class for returning the values associated with matrix object
        public override string ToString()
        {
            return string.Format("[a:{0};b:{1};c:{2}:d:{3}]", a,b,c,d );
        }
    }
}
// Add another class TestMatrix to test the above code.

using System;
namespace CSharpConsole
{
    class TestMatrix
    {
        static void Main()
        {
            Matrix m1 = new Matrix(5, 6, 7, 8);
            Matrix m2 = new Matrix(1, 2, 3, 4);
            Matrix m3 = m1 + m2;
            Matrix m4 = m1 - m2;
            Console.WriteLine(m1);
            Console.WriteLine(m2);
            Console.WriteLine(m3);
            Console.WriteLine(m4);
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment