You can redefine or overload most of the built-in operators available in C#. Thus a programmer can use operators with user-defined types as well. Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. similar to any other function, an overloaded operator has a return type and a parameter list.
For example:
For example:
using System; public class Program { int x, y, z; public Program() { x = y = z = 0; } public Program(int i, int j, int k) { x = i; y = j; z = k; } public static Program operator +(Program a, Program b) { Program c = new Program(); c.x = a.x + b.x; c.y = a.y + b.y; c.z = a.y + b.y; return c; } public static Program operator -(Program a, Program b) { Program c = new Program(); c.x = a.x - b.x; c.y = a.y - b.y; c.z = a.y - b.y; return c; } public void show() { Console.WriteLine(x + " , " + y + " , " + z); } } class second { static void Main(string[] args) { Program n1 = new Program(1,2,3); Program n2 = new Program(10,10,10); Program n3 = new Program(); Console.WriteLine("here is n1"); n1.show(); Console.WriteLine("here is n2"); n2.show(); n3 = n1 + n2; Console.WriteLine("Result of n1 + n2"); n3.show(); n3 = n1 + n2+n3; Console.WriteLine("Result of n1 + n2 + n3"); n3.show(); n3 = n3 - n1; Console.WriteLine("Result of n3 - n1"); n3.show(); n3 = n3 - n2; Console.WriteLine("Result of n3 - n2"); n3.show(); } }
Post A Comment:
0 comments: