Operators

This section describes what is operators, which are special methods that can be invoked in a syntax similar to arithmetic and comparison operations.

Operators are special methods in a class, which will allow objects of this class to invoke those methods in a syntax similar to the syntax of expression. The following program shows a simple currency class with some operators defined:

// Currency.cs
// Copyright (c) 2015, HerongYang.com, All Rights Reserved.

using System;
class Currency {
   private long v;
   public Currency(long value) {
      v = value*100;
   }
   public Currency(double value) {
      // value is rounded down after two decimal digits
      v = (long)(value*100.0);
   }
   public static implicit operator double(Currency a) {
      return a.v/100.0;
   }
   public static implicit operator Currency(double a) {
      return new Currency(a);
   }
   public static Currency operator+(Currency a, Currency b) {
      Currency c = new Currency(0);
      c.v = a.v+b.v;
      return c;
   }
   public static bool operator==(Currency a, Currency b) {
      return a.v == b.v;
   }
   public static bool operator!=(Currency a, Currency b) {
      return a.v != b.v;
   }
   public override string ToString() {
      if (v%100==0) return (v/100).ToString()+".00$";
      else return (v/100).ToString()+"."+(v%100).ToString()+"$";
   }
   public static void Main() {
      Currency a = new Currency(100); // constructor
      Currency b = 100.125; // conversion operator
      Currency c = b + b; // + operator
      Currency d = 100.1249; 
      Console.WriteLine("a = {0}.",a); // overrided ToString() 
      Console.WriteLine("b = {0}.",b);
      Console.WriteLine("c = {0}.",c);
      Console.WriteLine("b==d = {0}.",b==d); // == operator
   }
}

Output:

a = 100.00$.
b = 100.12$.
c = 200.24$.
b==d = True.

Last update: 2015.

Table of Contents

 About This Book

 Introduction of C# (C Sharp)

 Data Type and Variables

 Logical Expressions and Conditional Statements

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

Class Features

 "const" and "readonly" Variables

 Method Overloading

 Properties

Operators

 C# Compiler and Intermediate Language

 Compiling C# Source Code Files

 MSBuild - Microsoft Build Engine

 Memory Usages of Processes

 Multithreading in C#

 Async Feature from C# 5

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 WPF - Windows Presentation Foundation

 Partial Classes and Partial Methods

 Outdated Tutorials

 References

 PDF Printing Version