TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Math.Max and Min, Bounds-Checking

This C# article shows the Math.Max method. It rewrites if-statements.

Math.Max returns the larger value.

It can improve the style of code that calculates integer bounds. Often in algorithms we need to test if an integer is less than zero. We use Math.Max to test for these conditions with less code.

Note: Math.Max receives two numbers and returns the larger of the two arguments.

Note 2: Math.Max can be used to specify, in a single statement, a maximum value. It can encode a constraint, replacing an if-statement.

Example. This example uses the Math.Max method to check bounds. You can replace many if-statements with one line of code using Math.Max. We take the maximum of zero and the value. The result will never be less than zero.

Here: The GetLastIndex method internally uses the Math.Max function. It returns one index from the last index.

Return

Thus: If you pass in a number that is way too high, it won't cause an error in the calling code. It is safe and reliable.

C# program that uses Math

using System;

class Program
{
    static int[] _array = new int[]
    {
	1,
	2,
	5,
	6,
	7
    };

    static void Main()
    {
	// Get 1 place from end.
	int i = GetLastIndex(1);
	Console.WriteLine(i);

	// Get 3 places from end.
	i = GetLastIndex(3);
	Console.WriteLine(i);

	// Get 10 places from end. Will not throw exception.
	i = GetLastIndex(10);
	Console.WriteLine(i);
    }

    static int GetLastIndex(int length)
    {
	int start = _array.Length - length - 1;
	start = Math.Max(0, start);
	return _array[start];
    }
}

Output

6
2
1

Discussion. You will need to test again zero many times in your career as a developer. This is because using a negative number on the indexer will throw an exception. What you will get is an IndexOutOfRangeException, which Microsoft describes.

An IndexOutOfRangeException exception is thrown when an attempt is made to access an element of an array or collection with an index that is outside the bounds of the array or less than zero.

Troubleshooting Exceptions: MSDN

Also, I have benchmarked Math.Min and Math.Max and they are no different from typing the nine lines yourself. The only difference is that your code is shorter, simpler to read, and less prone to typos.

Example 2. Here we see another example of how you can rewrite if-statements to code that uses the Math class. This is important because with it you can impress your interviewers. It just makes your code more maintainable.

Code example that uses if: C#

using System;

class Program
{
    static void Main()
    {
	// Constrain indexes with if-statement.
	int a = 4;
	if (a < 0)
	{
	    Console.WriteLine(0);
	}
	else
	{
	    Console.WriteLine(a);
	}
    }
}

Code example that uses Math.Max: C#

using System;

class Program
{
    static void Main()
    {
	// Constrain indexes with Math.Max.
	int a = 4;
	Console.WriteLine(Math.Max(0, a));
    }
}

Math.Min. Next, we see how to rewrite an if-condition expression to use the method Math.Min on integral types. The following example caps values at a certain number using Math.Min. This code is efficient and often useful.

Math.Min

Caution: Sometimes the Math.Max and Math.Min methods can be confused. Be careful to test after rewriting code to use them.

Code that uses if: C#

using System;

class Program
{
    static void Main()
    {
	// Make sure it isn't > 10.
	int b = 15;
	if (b > 10)
	{
	    b = 10;
	}
	Console.WriteLine(b);
    }
}

Code that uses Math.Min: C#

using System;

class Program
{
    static void Main()
    {
	// Make sure it isn't > 10.
	int b = 15;
	Console.WriteLine(Math.Min(10, b));
    }
}

Summary. We clarified bounds-checking, simplified it, and impressed interviewers with Math.Min and Math.Max. There are many other methods on the Math static class, most of which can have similar effects on code quality.

Static Class


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf