Math.Max() Method in C#


The Math.Max() method in C# is used to return the larger of two specified numbers. This method works for both the numbers being Double, Decimal, Int16, Int32, etc.

Syntax

Following is the syntax −

public static ulong Max (ulong val1, ulong val2);
public static uint Max (uint val1, uint val2);
public static ushort Max (ushort val1, ushort val2);
public static float Max (float val1, float val2);
public static byte Max (byte val1, byte val2);
public static long Max (long val1, long val2);

Example

Let us now see an example to implement Math.Max() method −

using System;
public class Demo {
   public static void Main(){
      byte val1 = 10, val2 = 15;
      decimal val3 = 1000M, val4 = 1500M;
      double val5 = 15.896745, val6 = 25.676843;
      short val7 = 20, val8 = 30;
      Console.WriteLine("Maximum Value from two byte values = "+Math.Max(val1, val2));
      Console.WriteLine("Maximum Value from two decimal values = "+Math.Max(val3, val4));
      Console.WriteLine("Maximum Value from two double values = "+Math.Max(val5, val6));
      Console.WriteLine("Maximum Value from two short values = "+Math.Max(val7, val8));
   }
}

Output

This will produce the following output −

Maximum Value from two byte values = 15
Maximum Value from two decimal values = 1500
Maximum Value from two double values = 25.676843
Maximum Value from two short values = 30

Example

Let us see another example to implement Math.Max() method −

using System;
public class Demo {
   public static void Main(){
      int val1 = 10, val2 = 15;
      float val3 = 10.8f, val4 = 25.6f;
      Console.WriteLine("Maximum Value from two int values = "+Math.Max(val1, val2));
      Console.WriteLine("Maximum Value from two float values = "+Math.Max(val3, val4));
   }
}

Output

This will produce the following output −

Maximum Value from two int values = 15
Maximum Value from two float values = 25.6

Updated on: 06-Nov-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements