Hi Everyone,
Class.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication
{
class Dimesion
{
int ft, inch;
public Dimesion(int f,int i)
{
ft = f;
inch = i;
}
public static Dimesion operator +(Dimesion d1, Dimesion d2) //
Q.1) why 'public' & 'static' is necessary in operator overloading in C#? {
int f = d1.ft + d2.ft;
int i = d1.inch + d2.inch;
Dimesion d = new Dimesion(f, i);
return d;
}
/*
Public : It is an access modifier. we have declared public so that we can access the overloaded operator any where but if i want to access the overloaded operator in the inherited class only then I have to use protected instead of public but u can't write anything except public.
Static : This keyword is used when there is no need of creating an object of a class , you can directly call the data members with the help of class name but in the below code of form.cs we have created an object rather calling directly with the class name.
$$ */
public void Display()
{
MessageBox.Show(string.Format("Feet={0},Inch={1}", ft, inch));
}
}
}
Form.csusing 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 WindowsFormsApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Dimesion d1, d2, d;
private void button4_Click(object sender, EventArgs e)
{
d1 = new Dimesion(int.Parse(textBox1.Text), int.Parse(textBox2.Text)); //
$$ d1.Display();
}
private void button5_Click(object sender, EventArgs e)
{
d2 = new Dimesion(int.Parse(textBox3.Text), int.Parse(textBox4.Text)); //
$$ d2.Display();
}
private void button6_Click(object sender, EventArgs e)
{ //
$$ d = d1 + d2;
d.Display();
}
}
}
Q.2.) Why relational operators(< > <= >=) are overloaded in pairs? public static Dimesion operator +(Dimesion d1, Dimesion d2)
{
int f = d1.ft + d2.ft;
int i = d1.inch + d2.inch;
Dimesion d = new Dimesion(f, i);
return d;
}
above part of a code is written to overload '+' operator similarly if we have to write it for relational operators then we have to overload in pairs like if we have to overload '>' operator then we have to overload '<' operator also
public static Dimesion operator <(Dimesion d1, Dimesion d2)
{ }
public static Dimesion operator >(Dimesion d1, Dimesion d2)
{ }
// Program of overloading:
http://www.c-sharpcorner.com/UploadFile/prasadh/OperatorOverloading11142005003229AM/OperatorOverloading.aspxThanks & Regards
Rushal