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

About Brian McKay
Software Architect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: