Home Communities
IT Knowledge
Inspiration
Languages
EN

# C# / .NET - Math.Min() method example

0 points
Created by:
297

The Math.Min() function returns the smallest number from given numbers.

using System;

public class Program
{
public static void Main(string[] args)
{
int min = Math.Min(2, 5);
Console.WriteLine( min); // 2

Console.WriteLine( Math.Min(1, 2)); // 1
Console.WriteLine( Math.Min(1.5, 2.0)); // 1.5

Console.WriteLine( Math.Min(2, Double.NaN)); // NaN
}
}

## 1. Documentation

 Syntax namespace System { public static class Math { // ... public static byte Min(byte val1, byte val2) { ... } public static decimal Min(decimal val1, decimal val2) { ... } public static double Min(double val1, double val2) { ... } public static short Min(short val1, short val2) { ... } public static int Min(int val1, int val2) { ... } public static long Min(long val1, long val2) { ... } public static sbyte Min(sbyte val1, sbyte val2) { ... } public static float Min(float val1, float val2) { ... } public static ushort Min(ushort val1, ushort val2) { ... } public static uint Min(uint val1, uint val2) { ... } public static ulong Min(ulong val1, ulong val2) { ... } // ... } } Parameters val1, val2 - values to compare. Result Minimal number value (primitive value). It returns NaN if at least one of the provided values is not a number. Description Min is a static method that takes number arguments and returns the smallest one value.

## 2. Getting min value from array examples

### 2.1. With Min() method from System.Linq.

using System;
using System.Linq;

public class Program
{
public static void Main(string[] args)
{
int[] array = new int[] { 1, 5, 2, 16, -5 };

int min = array.Min();
Console.WriteLine(min); // -5
}
}

### 2.2. By comparing all the elements in the array

using System;

public class Program
{
static double Min(double[] array)
{
double result = Double.PositiveInfinity;
foreach (double currentNumber in array)
{
if (result > currentNumber) result = currentNumber;
}
return result;
}

public static void Main(string[] args)
{
double[] numbersArray = new double[] { 1.4, 5.0, 2.2, 16.0, -5.0 };

Console.WriteLine(Min(numbersArray)); // -5
}
}

## References

1. Maxima and minima - Wikipedia

Join to our subscribers to be up to date with content, news and offers.