For Asp.net Training with C#
Click Here
Written By:-Isha Malhotra
Email:-malhotra.isha3388@gmail.com
Operator Overloading
Before understanding the operator overloading we need to
understand why we use operator overloading. In the following example we have
one class calculator which contains two variable x and y. and one web form
where we create two variables in its cs file and add them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
int p = 10;
int q = 20;
int r = p + q;
}
}
In this operation we
didn’t get any problem but if we try to add two objects we will get error like
this:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
Calculator cal1 = new
Calculator();
cal1.x = 10;
cal1.y = 20;
Calculator cal2 = new
Calculator();
cal2.x = 15;
cal2.y = 25;
//we will get error that we cannot use + operator of type
Calculator(which is ref type)
Calculator cal = cal1 + cal2;
}
}