Thursday, September 1, 2011

C# Operator overloading

Whenever you overload an operator in C#, you have specific operator methods created that are related to the operator that you overload. Hence, when you overload the + operator, the overloaded operator method name is operator+. Note that all the overloaded operator methods are named "operator."  Further, all operator methods in C# are static.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace weight
{
    class weight
    {
        int kg;
        int mg;
        public weight()
        { }
        public weight(int a, int b)
        {
            kg = a;
            mg = b;
        }
        public void get_w()
    {
        Console.WriteLine("Enter the kilogram Object 2");
        kg = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the miligram Object 2");
        mg = Convert.ToInt32(Console.ReadLine());
    }
        public void display()
  {
Console.WriteLine("kilograms are   {0}  \nMile grams are  {1}", kg, mg);
}
        public static weight operator+(weight h1, weight h2)
        {
            int Kg, Mg;
            Kg = h1.kg + h2.kg;
            Mg = h1.mg + h2.mg;
            if (Mg >= 1000)
            {
                Kg++;
                Mg -= 1000;
            }
            else { }
            weight h3 = new weight(Kg, Mg);
            return h3;

        }
        static void Main(string[] args)
        {
            weight w1 = new weight(5, 600);
            weight w2 = new weight();
            w2.get_w();
            w2.display();
            w1.display();
            weight w3 = w1 + w2;
            w3.display();

        }
    }
Output
}

No comments:

Post a Comment

used in operatonal research LP(linear programming) The Simplex Algorithm Simplex method Resolve using the Simple...