Title: Make generic Min and Max methods in C#
This example shows how you can make generic Min and Max methods to find the minimum and maximum values in a sequence of parameters.
The Math namespace's Min and Max methods are very useful, but they have two big drawbacks. First, they take only two parameters. That means if you want to find the largest and smallest of more than two values, you need to use them repeatedly. The second drawback is that they only work with double parameters. If you pass ints or floats into the methods, the values are promoted to the double data type so the methods still work, but their results are doubles so you'll need to convert them if you want the results to have the original data types.
The following code defines a generic Max method that handles both of those problems.
// Return the largest of the values.
private T Max<T>(params T[] values) where T : IComparable<T>
{
T max = values[0];
for (int i = 1; i < values.Length; i++)
if (values[i].CompareTo(max) > 0) max = values[i];
return max;
}
The method has the generic type parameter T. The where clause requires that T implements the IComparable interface. That's necessary to allow the method to compare the values passed into the method as parameters.
The method's parameter list is a parameter array, so the program can pass in any number of parameters.
The method's code sets value max equal to the first parameter's value. It then loops through the rest of the values, comparing max with the other values. When it finds a value larger than max, the method updates max.
After it has examined all of the values, the method returns max.
The Min method is similar.
The following code shows how the main program tests the methods.
private Random Rand = new Random();
private void goButton_Click(object sender, EventArgs e)
{
int A = Rand.Next(1, 100);
int B = Rand.Next(1, 100);
int C = Rand.Next(1, 100);
int D = Rand.Next(1, 100);
int E = Rand.Next(1, 100);
txtValues.Text =
A.ToString() + " " +
B.ToString() + " " +
C.ToString() + " " +
D.ToString() + " " +
E.ToString();
txtMinimum.Text = Min(A, B, C, D, E).ToString();
txtMaximum.Text = Max(A, B, C, D, E).ToString();
}
This code defines a Random object. The form's Load event handler generates 5 random values and displays them in txtValues. It then calls the Min and Max methods and displays their results in two other textboxes.
Download the example to experiment with it and to see additional details.
