CSharp examples for Custom Type:Operator Overloading
The unary operators that can be overloaded are listed here:
UL: + - ++ -- ! ~ true false
The following code shows how to overload the + and - Unary Operators.
using System;/*from w w w . j av a2s . c om*/ using System.Text; 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 ) { MyCharacter result = new MyCharacter(); if( orig.ch >= 'a' && orig.ch <='z' ) result.ch = (char) (orig.ch - 32 ); else result.ch = orig.ch; return result; } static public MyCharacter operator- ( MyCharacter orig ) { MyCharacter result = new MyCharacter(); if( orig.ch >= 'A' && orig.ch <='Z' ) result.ch = (char) (orig.ch + 32 ); else result.ch = orig.ch; return result; } } public class myAppClass { public static void Main(String[] args) { MyCharacter aaa = new MyCharacter('g'); MyCharacter bbb = new MyCharacter('g'); MyCharacter ccc = new MyCharacter('G'); MyCharacter ddd = new MyCharacter('G'); Console.WriteLine("ORIGINAL:"); Console.WriteLine("aaa value: {0}", aaa.ch); Console.WriteLine("bbb value: {0}", bbb.ch); Console.WriteLine("ccc value: {0}", ccc.ch); Console.WriteLine("ddd value: {0}", ddd.ch); aaa = +aaa; bbb = -bbb; ccc = +ccc; ddd = -ddd; Console.WriteLine("\n\nFINAL:"); Console.WriteLine("aaa value: {0}", aaa.ch); Console.WriteLine("bbb value: {0}", bbb.ch); Console.WriteLine("ccc value: {0}", ccc.ch); Console.WriteLine("ddd value: {0}", ddd.ch); } }