Friday, January 11, 2013

MaxValue and MinValue in C#.NET Numerical Data Types


The numerical types of .NET support MaxValue and MinValue properties that provide information regarding the range a given type can store. Assume you have created some variables of type System.UInt16 (an unsigned short) and exercised it as follows:

static void Main(string[] args)
{
System.UInt16 myUInt16 = 30000;
Console.WriteLine("Max for an UInt16 is: {0} ", UInt16.MaxValue);
Console.WriteLine("Min for an UInt16 is: {0} ", UInt16.MinValue);
Console.WriteLine("Value is: {0} ", myUInt16);
Console.WriteLine("I am a: {0} ", myUInt16.GetType());

// Now in System.UInt16 shorthand (e.g., a ushort).

ushort myOtherUInt16 = 12000;
Console.WriteLine("Max for an UInt16 is: {0} ", ushort.MaxValue);
Console.WriteLine("Min for an UInt16 is: {0} ", ushort.MinValue);
Console.WriteLine("Value is: {0} ", myOtherUInt16);
Console.WriteLine("I am a: {0} ", myOtherUInt16.GetType());
Console.ReadLine();
}

In addition to the MinValue/MaxValue properties, a given system type may define further useful members. For example, the System.Double type allows you to obtain the values for Epsilon and
infinity values:

Console.WriteLine("-> double.Epsilon: {0}", double.Epsilon);
Console.WriteLine("-> double.PositiveInfinity: {0}", double.PositiveInfinity);
Console.WriteLine("-> double.NegativeInfinity: {0}", double.NegativeInfinity);
Console.WriteLine("-> double.MaxValue: {0}", double.MaxValue);
Console.WriteLine("-> double.MinValue: {0}",double.MinValue);

No comments:
Write comments
Recommended Posts × +