Operator is used to provide functionality or logic in between the data members or we can say it's a varibles of the class in c sharp.
But By using operator overloading concept we can provide functionality between the objects of the class.
For Example Addition of two variables which having the complex number.
Real and Imaginary part at that time we have to overload an operator and perform the addition of two complex number.
Example:- Console Application in Asp.net Visual Studio 2010.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operator_overloading
{
class Program
{
static void Main(string[] args)
{
Test t1 = new Test(10,100);
Console.WriteLine("\n\n\tThe information of t1");
t1.show();
Test t2 = new Test(11,111);
Console.WriteLine("\n\n\tThe information of t2");
t2.show();
Test t3 = new Test();
t3 = t1 + t2;
Console.WriteLine("\n\n\tAfter Addition of t1 and t2");
t3.show();
Test t4 = new Test();
t4=t3++;
t4.show();
Console.ReadLine();
}
}
class Test
{
int a, b;
public Test()
{
a = 0;
b = 0;
}
public Test(int n, int m)
{
a = n;
b = m;
}
public static Test operator +(Test t, Test tt)
{
Test temp = new Test();
temp.a = t.a + tt.a;
temp.b = t.b + tt.b;
return temp;
}
public static Test operator ++(Test t)
{
t.a++;
t.b++;
return t;
}
public void show()
{
Console.WriteLine("\n\t\tThe values are "+this.a+" and "+this.b);
}
}
}
OutPut

But By using operator overloading concept we can provide functionality between the objects of the class.
For Example Addition of two variables which having the complex number.
Real and Imaginary part at that time we have to overload an operator and perform the addition of two complex number.
Example:- Console Application in Asp.net Visual Studio 2010.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operator_overloading
{
class Program
{
static void Main(string[] args)
{
Test t1 = new Test(10,100);
Console.WriteLine("\n\n\tThe information of t1");
t1.show();
Test t2 = new Test(11,111);
Console.WriteLine("\n\n\tThe information of t2");
t2.show();
Test t3 = new Test();
t3 = t1 + t2;
Console.WriteLine("\n\n\tAfter Addition of t1 and t2");
t3.show();
Test t4 = new Test();
t4=t3++;
t4.show();
Console.ReadLine();
}
}
class Test
{
int a, b;
public Test()
{
a = 0;
b = 0;
}
public Test(int n, int m)
{
a = n;
b = m;
}
public static Test operator +(Test t, Test tt)
{
Test temp = new Test();
temp.a = t.a + tt.a;
temp.b = t.b + tt.b;
return temp;
}
public static Test operator ++(Test t)
{
t.a++;
t.b++;
return t;
}
public void show()
{
Console.WriteLine("\n\t\tThe values are "+this.a+" and "+this.b);
}
}
}
OutPut
No comments:
Post a Comment