Overloaded Operation in C#

C# has a special feature that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading. This code will help you understand overloaded operators.

Overloaded operation through C#

C# has a special feature that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading. This code will help you understand overloaded operators. It also uses some delegate techniques, and a bit of GDI+.

The bellow program shows a operator overloading capabilities with a vector class.

Vector class

using System;

namespace VectorAlgebra
{
    /// <summary>
    /// This class uses operator overloads
    /// to create algebraic vector points.
    /// </summary>

    public class Vector
    {
        public Vector(int x, int y)
        {
            m_x = x;
            m_y = y;
        }

        ~Vector(){}
   
    #region " Properties "
       
        private int m_x;
        public int X
        {
            get {return m_x;}
            set {m_x = value;}
        }

        private int m_y;
        public int Y
        {
            get {return m_y;}
            set {m_y = value;}
        }

    #endregion

    /* in this region we setup all of our overloaded operators, and
     * overriden methods/functions.
     * FYI,
     * Binary operators are operators that use 2 parameters
     * Unary operators are operators that use single parameter.*/

    #region " Overloaded operators "

        /* when we overload ==, by convention we must also overload
         * != operator, and (but not required) methods Equals, GetHashCode*/

        public static bool operator ==(Vector aVector, Vector bVector)
        {
            /*if both coordinates of both vectors is the same this
            will return true.*/

            return (aVector.X == bVector.X) && (aVector.Y == bVector.Y);
        }
       
        public static bool operator !=(Vector aVector, Vector bVector)
        {
            return !(aVector == bVector);
        }

        public override bool Equals(object o)
        {
            /*if the object is a vector object, and they are
             * both the same instance this will return true*/

            return (o is Vector) && (this == (Vector)o);
        }

        public override int GetHashCode()
        {
            return this.X;
        }

        //unary negative operator.
        public static Vector operator -(Vector vector)
        {
            return new Vector(-vector.X, -vector.Y);
        }

        public static Vector operator +(Vector aVector, Vector bVector)
        {
            return new Vector(aVector.X + bVector.X, aVector.Y + bVector.Y);
        }
       
        //binary minus operator.
        public static Vector operator -(Vector aVector, Vector bVector)
        {
            return aVector + (-bVector);
        }

        // will be used for operations like 2 * vectorA.
        public static Vector operator *(int scalar, Vector vector)
        {
            return new Vector(scalar * vector.X, scalar * vector.Y);
        }

        // will be used for operations like vectorA * 2.
        public static Vector operator *(Vector vector, int scalar)
        {
            return new Vector(vector.X * scalar, vector.Y * scalar);
        }

    #endregion

        public static Vector Parse(string vectorString)
        {
           
            try
            {
                string[] values = vectorString.Split("( ,)".ToCharArray());
                int x = int.Parse(values[1]);
                int y = int.Parse(values[3]);

                return new Vector(x,y);
            }
            catch
            {
                throw new ArgumentException("Unable to parse '" + vectorString
                    + "' into a Vector instance.");
            }
        }

        public override string ToString()
        {
            return string.Format("{0}, {1}", m_x, m_y);
        }

    }
}

Now look into the main class where the Vector class is instantiated.
This class does vector operation and also draws vectors on the screen using GDI+.
 
Main class

/// <summary>
        /// The main entry point for the application.
        /// </summary>

        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

       
        private void Form1_Load(object sender, System.EventArgs e)
        {
            /*add keys to the collection with the VectorMath
             * delegate as the object, so the proper method
             * will get executed depending on what they choose from the
             * list.*/

            m_maths.Add("Add", new VectorMath(AddVectors));
            m_maths.Add("Subtract", new VectorMath(SubtractVectors));
            m_maths.Add("Are equal", new VectorMath(AreEqual));

            //add the collections keys to the list.
            functions.DataSource = m_maths.Keys;
        }

        private void
Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            // draw the axis of our grid.
            e.Graphics.DrawLine(Pens.Black, 20, 170, 320, 170);
            e.Graphics.DrawLine(Pens.Black, 170, 20, 170, 320);
        }


        //converts vector x & y points to pixel positions on the form.
        private Point VectorToPoint(Vector vector)
        {
            return new Point(vector.X*15 + 170, -vector.Y*15 + 170);
        }

        // overloaded drawvector methods.
        private void DrawVector(Vector vector, Color color)
        {
            Point origin = VectorToPoint(new Vector(0,0));
            Point end = VectorToPoint(vector);

            this.CreateGraphics().DrawLine(
                new Pen(new SolidBrush(color),2), origin, end);
        }

        private void DrawVector(Vector aVector, Vector bVector, Color color)
        {
            Point origin = VectorToPoint(bVector);
            Point end = VectorToPoint(aVector + bVector);

            this.CreateGraphics().DrawLine(
                new Pen(new SolidBrush(color), 2), origin, end);
        }

        /* these properties will convert the values of the
         * numericupdown controls into Vector instances.*/

        private Vector VectorA
        {
            get
            {
                return new Vector((int)this.XVectorA.Value,
                    (int)this.YVectorA.Value);
            }
        }

        private Vector VectorB
        {
            get
            {
                return new Vector((int)this.XVectorB.Value,
                    (int)this.YVectorB.Value);
            }
        }

           
        private void AddVectors(Vector a, Vector b)
        {
            DrawVector(a, Color.Red);
            DrawVector(b, a, Color.Blue);

            //uses the overloaded binary '+' operator.
            Vector sum = a + b;

            DrawVector(sum, Color.Green);

            /*uses overriden ToString method to format the
             * vectors coordinate values into (,) format.*/

            this.result.Text = sum.ToString();
           
        }

        private void SubtractVectors(Vector a, Vector b)
        {
            DrawVector(a, Color.Red);
            DrawVector(-b, a, Color.Blue);

            // uses overloaded '-' operator
            Vector difference = a - b;

            DrawVector(difference, Color.Green);

            this.result.Text = difference.ToString();
        }

        private void
AreEqual(Vector a, Vector b)
        {
            /*check if the vectors coordinates are identical.
             * using the '==' overload.*/

            bool equal = (a==b);
            this.result.Text = equal.ToString();
        }

        /*this event will handle all of the X,Y Vector numericupdown controls
         * preforming the chosen math technique for creating points, and drawing
         * lines on the grid.*/

        private void VectorChanged(object sender, EventArgs e)
        {
            VectorMath theMath = (VectorMath)m_maths[functions.Text];
                                    //uses the overloaded '*' operator.
            theMath(this.VectorA, (int)scalar.Value * this.VectorB);
        }
    }
}

This is all about operator overloading and sample of GDI+.
Hope it helps in exploring more...

Thanks
Preetham
By preetham preetham   Popularity  (1159 Views)