CSharp examples for Custom Type:Operator Overloading
The general format for overloading an operator is shown here:
public static return_type operator op ( type x, type y ) { ... return return_type; }
using System;/*w w w . j a va 2 s . co m*/ public class MyCharacter { private char private_ch; public MyCharacter() { this.ch = ' '; } public MyCharacter(char val) { this.ch = val; } public char ch { get{ return this.private_ch; } set{ this.private_ch = value; } } static public MyCharacter operator+ ( MyCharacter orig, int val ) { MyCharacter result = new MyCharacter(); result.ch = (char)(orig.ch + val); return result; } static public MyCharacter operator- ( MyCharacter orig, int val ) { MyCharacter result = new MyCharacter(); result.ch = (char)(orig.ch - val); return result; } } public class myAppClass { public static void Main(String[] args) { MyCharacter aaa = new MyCharacter('a'); MyCharacter bbb = new MyCharacter('b'); Console.WriteLine("Original value: {0}, {1}", aaa.ch, bbb.ch); aaa = aaa + 25; bbb = bbb - 1; Console.WriteLine("Final values: {0}, {1}", aaa.ch, bbb.ch); } }