Page Stats
Visitor: 300
C#.Net Operator Overloading
In C#.Net, Operator overloading is declared in a same way as a method declaration, but with the operator keyword followed by the operator symbol which we are overloading. C#.Net requires that all operator overloading be declared as public and static.
Example 1 : Overload + operator and find Sum of 2 numbers.
namespace operator_sum { class overload { int a; public void input() { Console.WriteLine("Enter number: "); a = Convert.ToInt32(Console.ReadLine()); } public void output() { Console.WriteLine("Value = " + a); } public static overload operator+(overload obj1 , overload obj2) { overload obj = new overload(); obj.a = obj1.a + obj2.a; return obj; } } class Program { static void Main(string[] args) { overload obj1 = new overload(); overload obj2 = new overload(); overload obj3 = new overload(); obj1.input(); obj2.input(); obj3 = obj1 + obj2; //operator overload call obj3.output(); Console.ReadLine(); } } }
Example 2 : Overload > operator and find Greater number from 2 input numbers.
namespace operator_greater { class greater { int a; public void input() { Console.WriteLine("Enter number"); a = Convert.ToInt32(Console.ReadLine()); } public static greater operator >(greater g1, greater g2) { if (g1.a > g2.a) return g1; else return g2; } public static greater operator <(greater g1, greater g2) { if (g1.a < g2.a) return g1; else return g2; } public void output() { Console.WriteLine("Value = " + a); } } class Program { static void Main(string[] args) { greater g1 = new greater(); greater g2 = new greater(); greater g3 = new greater(); g1.input(); g2.input(); g3 = g1 > g2; //operator '>' overload call g3.output(); g3 = g1 < g2; //operator '>' overload call g3.output(); Console.ReadLine(); } } }
- Input 2 numbers and find smallest number.
- Input 2 names and find it is equal or not, overload == operator.
- Input 2 names and find greater, overload > operator.