It's sometimes important to find the max value of an integer. Every typed number in C# has a specific max value, but that number is different for int, uint, short, and ushort. Use the int.MaxValue, int.MinValue, and related constants for clearer programs.
First let's look at MSDN to see what Microsoft says. They say that MaxValue is a "public const int". With a bit of exploration, I found this information about the MaxValue and MinValue constants.
| Field | Value |
| short.MaxValue | 32767 |
| short.MinValue | -32768 |
| ushort.MaxValue | 65535 |
| ushort.MinValue | 0 |
| int.MaxValue | 2,147,483,647 |
| int.MinValue | -2,147,483,648 |
| uint.MaxValue | 4,294,967,295 |
| uint.MinValue | 0 |
| long.MaxValue | 9,223,372,036,854,775,807 |
| long.MinValue | -9,223,372,036,854,775,808 |
| double.MinValue double.MaxValue | Really small Really big |
The above fields are constants and can be accessed anywhere with the name in the left column. By using these constants, you can avoid typing out 10-digit numbers in your programs. However, they are not infinity.
You can 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. Look at this.
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);
}
}
// Results:
// 10000 (lower than int.MaxValue)
// 600
// 1
}
}Beware edges. When you start your tracking variable at MaxValue, you will want to know the constraints in your program. If the MaxValue can occur, then you will need to be very careful with the logic. It would work correctly here though.
In C# and Windows, there is no performance boost in using smaller data types in loops. Using ushort instead of int just creates unclear code. However, always prefer ushort and short (and also byte) for data structures, because that reduces memory use.
When you have other constants to define, follow Microsoft's example and declare them as "public const int ValueName". This has great performance and is standard, and also very clear for other developers to read. It works well with IntelliSense.
Nullable types. Instead of using int.MaxValue and int.MinValue, consider nullable types (they can be used with Nullable<int> or 'int?'). However, the public constants are simpler to read and understand and more efficient.
Don't type out numbers like -2,147,483,648 unless you have to--and here you don't have to. Use Microsoft's public constants for fast and clear code. Sometimes it's effective to start an int at int.MaxValue when you are looking for the lowest value in a loop.