Monday 2 September 2013

What is Operator Overloading in C# .Net

Operator Overloading

All the operators in C# have their specific meaning and functionality; for example the + operator adds two numeric numbers and the – operator subtracts two numeric values. However, sometimes, you may need to change the default functionality of an operator. For example, you may want to use the + operator add two complex numbers. As you know a complex number comprises a real number and an imaginary number; therefore, you cannot use the + operator to directly add two complex numbers. In such a situation, you can use operator overloading to assign a new meaning and functionality to an existing operator. Operator overloading is mechanism of assigning new functionality to an operator, in addition to the already specified functionality of the operator.

Example with Operator Overloading

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Polymorphism
{
public partial class OperatorOverloading : Form
{
public OperatorOverloading()
{
InitializeComponent();
}

class Complex
{
int x, y;
public Complex(int real, int imag)
{
x = real;
y = imag;
}

public static Complex operator +(Complex c1, Complex c2)
{
Complex c3 = new Complex(c1.x + c2.x, c1.y + c2.y);
return c3;
}

public override string ToString()
{

return x + "+" + y +" "+ "i";
}
}

private void button1_Click(object sender, EventArgs e)
{
Complex a = new Complex(Convert.ToInt32(txtrno1.Text),Convert.ToInt32(txtino1.Text));
Complex b = new Complex(Convert.ToInt32(txtrno2.Text), Convert.ToInt32(txtino2.Text));
Complex c = a + b;
lblcomplexno1.Text="First Complex No=" + a.ToString();
lblcomplexno2.Text = "Second Complex No=" + b.ToString();
lblcomplexresult.Text="Addition of Complex No ="+ c.ToString();
}
}
}

0 comments:

Post a Comment