C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
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.
Tip: The C# language has complex rules for implicit casting, so this may occur when using Math.Min or similar Math methods.
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
In both uses of Math.Min, the smaller of the two values (the identifiers value1, and value3) are returned. You cannot use null as a parameter or any reference type. The number zero also works well with Math.Min.
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, as shown below, 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.