Wednesday, August 3, 2011

C# int.Max and Min Constants


You need minimum and maximum values in your program, such as by using int.MaxValue andint.MinValue. Every integer or typed number in the C# language has a specific max value, but that number is different for int, uint, short, and ushort. Here we see the values of and examples for these constants.

Values

First, here we look at MSDN to see what Microsoft says. It states that MaxValue is a "public const int". With a bit of exploration, I found this information about the MaxValue and MinValue constants.

short.MaxValue32767

short.MinValue-32768

ushort.MaxValue65535

ushort.MinValue0

int.MaxValue2,147,483,647

int.MinValue-2,147,483,648

uint.MaxValue4,294,967,295

uint.MinValue0

long.MaxValue9,223,372,036,854,775,807

long.MinValue-9,223,372,036,854,775,808

double.MinValueReally small

double.MaxValueReally big
Numbers. The above fields are constants and can be accessed anywhere with the composite name. By using these constants, you can avoid typing out 10-digit numbers in your programs. However, they are not equivalent to infinity.

Example

Here we clarify the logic in loops. One problem I have dealt with is keeping track of the lowest number found. You can use int.MaxValue to start the value really high, and then any lower number will be valid.
Program that uses int.MaxValue [C#]

using System;

class Program
{
    static void Main()
    {
 int[] integerArray = new int[]
 {
     10000,
     600,
     1,
     5,
     7,
     3,
     1492
 };

 // This will track the lowest number found
 int lowestFound = int.MaxValue;

 foreach (int i in integerArray)
 {
     // By using int.MaxValue as the initial value,
     // this check will succeed (almost) always.
     if (lowestFound > i)
     {
  lowestFound = i;
  Console.WriteLine(lowestFound);
     }
 }
    }
}

Output
    (All values are lower than int.MaxValue)

10000
600
1