Operator Overloading is defined as a process of defining and implementing the polymorphism technique. Operator Overloading in C# is consists of operators which are functions with special names the keyword operator followed by the symbol for the operator being defined.
Syntax:
Given below is the syntax of operator overloading implementation,
Overloading can be done on both Unary operators and Binary operators.
The details are given below:
Binary Operators Overloading:
Overloading can be done on Binary operators such as +, -, *, /, %, &, |, <<, >>.
Syntax:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OperatorOverloading { public class Marks { public int num; public Marks() { num = 0; } public Marks(int n) { num = n; } public static Marks operator +(Marks s1, Marks s2) { Marks s3 = new Marks(); s3.num = s1.num + s2.num + s3.num; return s3; } public void display() { Console.WriteLine("{0}", num); } } public class Program { public static void Main(string[] args) { Marks num = new Marks(69); Marks num1 = new Marks(98); Marks num2 = new Marks(76); Marks num3 = new Marks(); num3 = num + num1 + num2; num.display(); num1.display(); num2.display(); num3.display(); } } }
Unary Operators Overloading:
Overloading can be done on both Unary operators like ++, –, true, false, + , -, ~.
Syntax:
using System; namespace OperatorOverloading { public class number { public int val1, val2; public number(int no1, int no2) { val1 = no1; val2 = no2; } public number() { } public static number operator -(number eg1) { eg1.val1 = -eg1.val1; eg1.val1 = -eg1.val1; return eg1; } public void Print() { Console.WriteLine("value1 =" + val1); Console.WriteLine("value2 =" + val2); } } public class Program { public static void Main(string[] args) { number eg = new number(46,-78); eg.Print(); number eg1 = new number(); eg1 = -eg; eg1.Print(); } } }