C# Math.Min Method

This C# example program shows the Math.Min method from the .NET Framework.
Math.Min returns the smaller of two numbers. This can be done easily with if-statements. But the Math.Min method provides a way that is more error-proof. It is sometimes simpler to read.Math.Max
Example. First, we describe Math.Min in general. The Math.Min method returns the minimum of the two arguments you send to it. You need to send two numbers of the same type, such as int, uint, double or decimal.Int, uintDoubleDecimal

Casting: The C# language has complex rules for implicit casting, so this may occur when using Math.Min or similar Math methods.

Numeric Promotion

Info: In both uses of Math.Min, the smaller of the two values (the identifiers value1, and value3) are returned.

Also: You cannot use null as a parameter or any reference type. The number zero can be used with Math.Min.

C# program that uses Math.Min using System; class Program { static void Main() { // // Use Math.Min on positive integers. // int value1 = 4; int value2 = 8; int minimum1 = Math.Min(value1, value2); Console.WriteLine(minimum1); // // Use Math.Min on negative and positive integers. // int value3 = -1000; int value4 = 100; int minimum2 = Math.Min(value3, value4); Console.WriteLine(minimum2); } } Output 4 -1000
Implementation. We look at how Math.Min is implemented in the base class library that is used in the .NET Framework. Internally, the Math.Min overload for Int32 returns the result of an if-conditional.

However: I found that the Math.Min methods for decimal and float contain additional processing only for those types.

Internal implementation of Min: C# [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Min(int val1, int val2) { if (val1 > val2) { return val2; } return val1; }
Summary. We used the Math.Min method. We also looked into its implementation in the base class library. This method is useful for bounds-checking, such as when you want to find the lowest offset in an array but do not want to go below zero.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls