Languages
[Edit]
EN

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

0 points
Created by:
Mohammad-Oneal
237

The Math.Max() function returns the highest number from given numbers.

using System;

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

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

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

1. Documentation

Syntax
namespace System
{
    public static class Math
    {
        // ...
        public static byte Max(byte val1, byte val2) { ... }
        public static decimal Max(decimal val1, decimal val2) { ... }
        public static double Max(double val1, double val2) { ... }
        public static short Max(short val1, short val2) { ... }
        public static int Max(int val1, int val2) { ... }
        public static long Max(long val1, long val2) { ... }
        public static sbyte Max(sbyte val1, sbyte val2) { ... }
        public static float Max(float val1, float val2) { ... }
        public static ushort Max(ushort val1, ushort val2) { ... }
        public static uint Max(uint val1, uint val2) { ... }
        public static ulong Max(ulong val1, ulong val2) { ... }
        // ...
    }
}
Parametersval1, val2 - values to compare.
Result

Maximal number value (primitive value).

It returns NaN if at least one of the provided values is not a number.

DescriptionMax is a static method that takes number arguments and returns the biggest one value.

2. Getting max value from array examples

2.1. With Max() 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 max = array.Max();
        Console.WriteLine( max ); // 16
    }
}

2.2. By comparing all the elements in the array

using System;

public class Program
{
    static double Max(double[] array)
    {
        double result = Double.NegativeInfinity;
        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( Max( numbersArray ) ); // 16
    }
}

References

  1. Maxima and minima - Wikipedia

C# / .NET - Math object

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join