Overloading Binary Operators in C#
In this article . I offers learner on Overloading Binary operators. These operators work with two operands. Examples of binary operators and more description about Binary Operators Overloading are given hereunder.
In This article I represent Overloading Binary Operators in C# which help use for Binary Operators . It include the arithmetic operators (+,-,*,/),arithmetic assignment operators (+=,-+,*=,/=) and comparison operators. You can overload simple binary operators. Binary operators are used as shown in the following code :-
x <operator> y in the preceding code ,<operator> is a symbol that denotes a binary.C# interprets the expression as : operator <operator >(Firstobject,Secondobject)
The code snippet as given below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Sum
{
public int a;
public Sum()
{
a = 0;
}
public Sum(int num)
{
a = num;
}
public static Sum operator +(Sum c1, Sum c2)
{
Sum c3 = new Sum();
c3.a = c1.a + c2.a;
return c3;
}
public void display()
{
Console.WriteLine("value of "+a);
}
}
class Program
{
static void Main(string[] args)
{
Sum num1 = new Sum(70);
Sum num2 = new Sum(50);
Sum num3 = new Sum();
num3 = num1 + num2;
num1.display();
num2.display();
num3.display();
Console.Read();
}
}
}
output:
value of 70
value of 50
value of 120
Good Article