This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming

Representing Infinity in C#

When performing mathematical operations, it is possible to obtain a result that is either positive or negative infinity. C# and the .NET framework permit this result and allow storage of infinite values within selected floating-point structures.

Storing Infinity

Some mathematical operations can return an infinite value as their result. For example, when dividing any positive value by zero, the result is infinity. Similarly, dividing any negative value by zero returns a result of negative infinity.

In many programming languages, and for some data types in C#, this type of operation throws a division by zero exception. However, if you are using single-precision or double-precision floating point numbers, the infinite value can be calculated and stored correctly.

To demonstrate this, try executing the following code. This sample divides two values by zero and outputs the results. Note that the zero value is held in a variable, as the C# compiler will prevent you from building a project where a direct division by zero is present:

float zero = 0;

float positive = 1 / zero;
Console.WriteLine(positive);    // Outputs "Infinity"

float negative = -1 / zero;
Console.WriteLine(negative);    // Outputs "-Infinity"

Infinity Constants

The float and double structures represent infinity using two static fields, named PositiveInfinity and NegativeInfinity. These values can be directly assigned to variables or used for comparison purposes.

double positive = double.PositiveInfinity;
double negative = double.NegativeInfinity;

Console.WriteLine(negative == double.NegativeInfinity);     // Outputs "True"

Testing for Infinity

Rather than using a comparison as shown above, you can test if a value is infinite using one of three static methods of the float and double structures. The IsInfinity method returns a Boolean value that is true if the value passed as a parameter is either positive or negative infinity. To check for either positive or negative infinity specifically, you can use either of the IsPositiveInfinity or IsNegativeInfinity methods.

float zero = 0;

float positive = 1 / zero;

Console.WriteLine(double.IsInfinity(positive));             // Outputs "True"
Console.WriteLine(double.IsPositiveInfinity(positive));     // Outputs "True"
Console.WriteLine(double.IsNegativeInfinity(positive));     // Outputs "False"
18 December 2008