Last active
April 26, 2023 13:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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