Tip: How to Concatenate a Required Argument to a Params Array

Here’s a simple trick that allows you to quickly add a required method argument to a params array of the same type.

The example method below simply returns the minimum of all integers passed into the method where at least one integer is required.

        private static int Min(int value1, params int[] valuesArray)
        {
            int? minFromArray = null;

            if(valuesArray != null)
                minFromArray = valuesArray.Min();

            return (minFromArray.HasValue && minFromArray.Value < value1 ? minFromArray.Value : value1;
        }

A trick to turn the method into one line of code is to use the Concat method.

        private static int Min(int value1, params int[] valuesArray)
        {
            return valuesArray.Concat(new[] { value1 }).Min();
        }
Advertisements