November 19, 2017
operator overloading simple example
The operator overloading allows the operators e.g., +, -, /, *, etc to operate on operands of non primitive/basic data types, such as int, float, double, etc. The following example explains operator overloading:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication8 { class Money { public int money; public int MoneySum { get { return money; } } public Money() { } public Money(int money) { this.money = money; } public static Money operator + (Money m1, Money m2) { Money ans = new Money(); ans.money = m1.money + m2.money; return ans; } public static Money operator -(Money m1, Money m2) { Money ans = new Money(); ans.money = m1.money - m2.money; return ans; } public static Money operator *(Money m1, Money m2) { Money ans = new Money(); ans.money = m1.money * m2.money; return ans; } } class Program { static void Main(string[] args) { Money m1 = new Money(1); Money m2 = new Money(2); Money m3 = new Money(3); Money m4 = new Money(4); Money m5 = new Money(5); Money ans = m1 + m2 - m3 * m4 - m5; Console.WriteLine(ans.MoneySum); } } }