Summary

Quite often we want to be able to perform the same operation on some information given a differing number of arguments.  Typically, you might pass these arguments in as an array, thus avoiding the need to specify the number of arguments.  In order to call a function like this, we then need to go ahead and build and array of to pass in our arguments.  To me that seems like a little bit of an effort, at each point in my application, I know how many things I want to pass in.  So how else can I do this?

Solution

Now, consider the funtion System.String.Format().  In one form, the Format function can take a string and an array of type Objects.  A typical call to String.Format will be as follows:

string myString = System.String.Format(
    "Employee #{0} had been with the company since {1}{2}",
    currentEmployee.Number,
    currentEmployee.ContractCommenceDate.ToShortDateString(),
    Environment.NewLine
    );

Notice that our array of objects is represented as a comma separated list.  Lets see what happens if we try this and create a simple console application as follows:

using System;
using System.Text;

namespace VariadicFunctions
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(
                Concat(
                    "String 1 ",
                    "String 2 ",
                    "Stirng 3 "
                    )
                );
        }

        /// <summary>
        /// Glue a lots of strings together in to the mother of all strings.
        /// </summary>
        /// <param name="myStrings">A collection of obedient strings</param>
        /// <returns>The mother of all strings</returns>
        public static String Concat(string[] myStrings)
        {
            StringBuilder sBuild = new StringBuilder();

            foreach (String str in myStrings)
            {
                sBuild.Append(str);
            }

            return sBuild.ToString();
        }
    }
}

When we compile, we get an error telling us "No overload for method 'Concat' takes '3' arguments".  That makes sense, the method is looking for a string array, not a load of separate strings.  What we need to do is turn this in to what is know as a Variadic Function.

A variadic functions is a function that takes an variable number of arguments.  Essentially, to turn our function 'Concat' in to a variadic function we just need to use the params keyword.  What this keyword does is, in simple-speak, allows us to enter our additional arguments in a comma separated list.  Simply adding this keyword in will then allow us to comma-separate our arguments:

using System;
using System.Text;

namespace VariadicFunctions
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(
                Concat(
                    "String 1 ",
                    "String 2 ",
                    "Stirng 3 "
                    )
                );
        }

        /// <summary>
        /// Glue a lots of strings together in to the mother of all strings.
        /// </summary>
        /// <param name="myStrings">A collection of obedient strings</param>
        /// <returns>The mother of all strings</returns>
        public static String Concat(params string[] myStrings)
        {
            StringBuilder sBuild = new StringBuilder();

            foreach (String str in myStrings)
            {
                sBuild.Append(str);
            }

            return sBuild.ToString();
        }
    }
}

And there we go, no build errors, we can add as many stings as we like without issue.

References: 

Keywords:

  • Variadic, params, arguments array, variable arguments, variable parameters, parameters array

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Friday, September 12, 2008 6:02 PM | in .Net Framework

Comments

No comments posted yet.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 5 and 5 and type the answer here: