Posted by: Cirilo Meggiolaro | 02/12/2009

Tip of the day #121 – Variable number of parameters with params keyword (C#)

You may have noticed some built-in methods from .NET Framework that accept a variable number of parameters i.e. Console.WriteLine that you may use to format an output. The following code demonstrates that:

Console.WriteLine(“Tip of the day #{0} – Date: {0}”, 121, DateTime.Now.ToShortDateString());

If you take a look into the almost 20 WriteLine method overloads you are going to find the following signature:

public static void WriteLine(string format, params object[] arg);

Notice the params keyword before the array data type. The idea of the C# params keyword is to give a clue to the compiler that calls to this method may be resolved even though no parameters have been provided. To implement you need to follow some rules:

  • The parameter must be the last in the definition;
  • The parameter array must be a single-dimension array;
  • Only one params keyword is allowed per method.

It’s important to say that the params keyword is a wrapper to the ParamArrayAttribute that is not supported by C#. If you are developing in VB.NET you must use the ParamArray attribute to your method.

Example

The following method demonstrates how to create a method that may receive variable number of parameters and based on those parameters, write them to the console:

private static void WriteText(params string[] text)
{
    foreach (string item in text)
    {
        Console.WriteLine(“{0} “, item);
    }
}

WriteText(“Tip”, “of”, “the”, “day”, “#121”);

Output: Tip of the day #121

Advertisements

Responses

  1. That makes me remember Computer Science classes… Nice work.


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

Categories

%d bloggers like this: