How to use Overloading plus operator in C#


Introduction:
In this articles we will see how to use overloading plus operator in C#. A static method Fraction takes two integer parameters and return a fraction output and display the output as string type.operator overloading permits user -defined operator implementations to be specified for operation where one or both the operands are of a user defined class or struct type . 
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace
OverloadingPlusOperator
{
    class Calculate

   {
        public void calc()
        {
            Fraction Fraction1 = new Fraction(388,6677);
            Console.WriteLine("The fraction 1 is :{0}", Fraction1.ToString());
            Fraction Fraction2 = new Fraction(205, 47);
            Console.WriteLine("The fraction 2 is :{0}", Fraction2.ToString());
            Fraction sum = Fraction1 + Fraction2;
            Console.WriteLine("THe output of fraction 1 + fraction2 is :{0}", sum.ToString());
        }

        static void Main()
        {
            Calculate ca =new Calculate();
            ca.calc();
        }
    }
    public class Fraction
    {
        private int numerator;
        private int denominator;

        public Fraction(int numerator,int denominator)
        {

            this.numerator=numerator;
            this.denominator= denominator;
        }

        public static Fraction operator+(Fraction frac1,Fraction frac2)
        {
            if(frac1.denominator==frac2.denominator)
            {
                return new Fraction(frac1.numerator+frac2.numerator,frac1.denominator);
            }
            int product1=frac1.numerator*frac2.denominator;
            int product2=frac2.numerator*frac1.denominator;
            return new Fraction(product1+product2,frac1.denominator*frac2.denominator);
        }
        public override string  ToString()
        {
            string show =numerator.ToString()+"/"+denominator.ToString();
                return show;
        }
    }
}
Output of the program:
overloading-plus.gif

Ebook Download
View all
Learn
View all