Skip to content

Instantly share code, notes, and snippets.

@seekeroftheball
Last active April 26, 2023 13:46
Show Gist options
  • Save seekeroftheball/9c8ed33478f3907591588f0232195457 to your computer and use it in GitHub Desktop.
Save seekeroftheball/9c8ed33478f3907591588f0232195457 to your computer and use it in GitHub Desktop.
FindMax for a variable number of parameters of any IComparable type, returns the largest value from the provided parameters.
// using System;
// using System.Linq;
/// <summary>
/// Find the maximum value from a variable number of parameters of any IComparable type.
/// </summary>
/// <typeparam name="T">Type of paramaters to compare.</typeparam>
/// <param name="max">Variable number of parameters of any type that implements the IComparable<T> interface.</param>
/// <returns>The largest value from the provided parameters.</returns>
public T FindMax<T>(params T[] max) where T : IComparable<T>
{
T largestValue = max.Max();
return largestValue;
}
// Implementation examples:
private void Example()
{
// Max ints
int maxInt = FindMax(12, 7, 21, 4, 18); // returns 21
// strings comparing char by char
string[] strings = { "dog", "rock", "robot", "ham" };
string largestString = FindMax(strings); // returns "rock"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment