Jon Jagger
jon@jaggersoft.com
Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specificationpreviousnextprevious at this levelnext at this level 8 Language Overviewprevious at this levelnext at this level 8.7 Classesprevious at this levelnext at this level 8.7.6 OperatorsAn operator is a member that defines the meaning of an expression operator that can be applied to instances of the class. There are three kinds of operators that can be defined: unary operators, binary operators, and conversion operators. The following example defines a Digit type that represents decimal digits-integral values between 0 and 9.
using System;  
public struct Digit  
{  
   byte value;  
   public Digit(byte value) {  
      if (value < 0 || value > 9) throw new ArgumentException();  
      this.value = value;  
   }  
   public Digit(int value): this((byte) value) {}  
   public static implicit operator byte(Digit d) {  
      return d.value;  
   }  
   public static explicit operator Digit(byte b) {  
      return new Digit(b);  
   }  
   public static Digit operator+(Digit a, Digit b) {  
      return new Digit(a.value + b.value);  
   }  
   public static Digit operator-(Digit a, Digit b) {  
      return new Digit(a.value - b.value);  
   }  
   public static bool operator==(Digit a, Digit b) {  
      return a.value == b.value;  
   }  
   public static bool operator!=(Digit a, Digit b) {  
      return a.value != b.value;  
   }  
   public override bool Equals(object value) {  
      if (value == null) return false;  
      if (GetType() == value.GetType()) return this == (Digit)value;  
   return false;  }  
   public override int GetHashCode() {  
      return value.GetHashCode();  
   }  
   public override string ToString() {  
      return value.ToString();  
   }  
}  
class Test  
{  
   static void Main() {  
      Digit a = (Digit) 5;  
      Digit b = (Digit) 3;  
      Digit plus = a + b;  
      Digit minus = a - b;  
      bool equals = (a == b);  
      Console.WriteLine("{0} + {1} = {2}", a, b, plus);  
      Console.WriteLine("{0} - {1} = {2}", a, b, minus);  
      Console.WriteLine("{0} == {1} = {2}", a, b, equals);  
   }  
}  
The Digit type defines the following operators:
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS