Math

C# and the BCL provide a rich set of features that make math-oriented programming easy and efficient.

This section identifies some of the most common types applicable to math programming and demonstrates how to build new math types. The types mentioned in this section exist in the System namespace.

Language Support for Math

C# has many useful features for math, and can even build custom mathematical types. Operator overloading allows custom mathematical types, such as complex numbers and vectors, to be used in a natural way. Rectangular arrays provide a fast and easy way to express matrices. Finally, structs allow the efficient creation of low-overhead objects. For example:

struct Vector {
  float direction;
  float magnitude;
  public Vector(float direction, float magnitude) {
    this.direction = direction;
    this.magnitude = magnitude;
  }
  public static Vector operator *(Vector v, float scale) {
    return new Vector(v.direction, v.magnitude * scale);
  }
  public static Vector operator /(Vector v, float scale) {
    return new Vector(v.direction, v.magnitude * scale);
  }
  ...
}
class Test {
  static void Main( ) {
  Vector [,] matrix = {{new Vector(1f,2f), new Vector(6f,2f)},
                       {new Vector(7f,3f), new Vector(4f,9f)}};
  for (int i=0; i<matrix.GetLength(0); i++)
    for (int j=0; j<matrix.GetLength(1); j++)
      matrix[i, j] *= 2f;
}

Special Types and Operators

The decimal datatype is useful for financial calculations, since it is a base10 number that can store 28 to 29 significant figures (see Section 2.2.5.3 in

Get C# Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.