Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0142 Operator overloading

We can extend the meaning of an existing operator by overloading it. For example, C# overloads the + to do the string concatenation. The following operators are overloadable: + (unary) - (unary) ! ? ++ -- + - * / % & | ^ << >> == != > < >= <= To implement operators, define static methods to overload the operator. The following fragment shows a method that implements the addition operator (+) for adding two instances of the type Text: public static Text operator +(Text t1, Text t2) The following declares a method that overrides the operator for adding Text and an int: public static Text operator +(Text w, int i) We can use the operator like this: Text newText = text1 + 1; Note that the order of the arguments is important. The fragment defines the behavior for a Text + int operation, but not int + Text. We would need to define another method to support both orderings. The following code overloads the + operator: using System; using System.IO; public struct MyValue { int value; public MyValue(int semitonesFromA) { value = semitonesFromA; } public static MyValue operator +(MyValue x, int semitones) { return new MyValue(x.value + semitones); } } class Test { static void Main() { MyValue B = new MyValue(2); MyValue C = B + 2; } } The following example defines the type Text, which has two overridden addition operators: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Dynamic; public class Text { public string MyString { get; set; } public static string operator +(Text w1, Text w2) { return w1.MyString + " " + w2.MyString; } public static Text operator +(Text w, int i) { return new Text() { MyString = w.MyString + i.ToString() }; } public override string ToString() { return MyString; } } public class MainClass { static void Main(string[] args) { Text word1 = new Text() { MyString = "Hello" }; Text word2 = new Text() { MyString = "World" }; Console.WriteLine("Word1: {0}", word1); Console.WriteLine("Word2: {0}", word2); Console.WriteLine("Added together: {0}", word1 + word2); Console.WriteLine("Added with int: {0}", word1 + 7); } } The output: Word1: Hello Word2: World Added together: Hello World Added with int: Hello7