The “params” keyword in C#

In the past few weeks, for some odd reason, the issue of the “params” keyword came up a few times and several people asked “what does ‘params’ do?”.

So, I thought I’d just explain that here for those that are interested. The “params” keyword in C# (ParamArray in VB.NET) allows you to specify a variable number of parameters to a function. Now wait, you’re probably going to say “Robert, everyone knows you hate loose-typing, what kind of crazy-talk is this?”. But params actually serves a very specific purpose, and saves some code.

Here’s a formal definition from MSDN.

First, let’s talk about syntax. Perhaps the most common scenario where you already use params, is String.Format(). Take a look:

image

So what does that mean, exactly? Well, that means string.Format() takes in exactly one argument of type string (called format), and then you can pass in an optional number of object arguments too. This means that all of these will work – all because of “params”:

string output1 = String.Format("Test");

string output2 = String.Format("Test {0}", firstName);

string output3 = String.Format("Test {0} {1}", firstName, lastName);

string output4 = String.Format("Test {0} {1} from {2}", firstName, lastName, city); 

As you can see, you can pass in 0, 1, 2, 3, or more parameters. This is really just a language shortcut. What is basically doing is just making object[] (in this case) easier to use. Consider the alternative, if the params argument wasn’t there:

string output1 = String.Format("Test", null);

string output2 = String.Format("Test {0}", new object[] { firstName });

string output3 = String.Format("Test {0} {1}", new object[] { firstName, lastName });

string output4 = String.Format("Test {0} {1} from {2}", new object[] { firstName, lastName, city });

this is obviously not as readable, and more code. I assume because this is a common pattern, they decided to make this a language feature. As a developer, when is it appropriate to use? Well, I think string.Format() is a good use. An example that we used in class we give is the notion of a an “average” method, which figures out the average of many numbers. For example:

public int Average(params int[] numbersToAverage)

{

    int count = numbersToAverage.Length;

    int sum = 0;

 

    for (int index = 0; index < count; index++)

    {

        sum += numbersToAverage[index];

    }

 

    return sum / count;

}

Keep in mind this is a simple example with no error handling, but the point is to show how this would now be pretty easy to consume. You could then do something like this:

int result1 = Average(1, 3);

int result2 = Average(1, 2, 3, 4, 5, 6, 7, 8);

int result3 = Average(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144);

The takeaway from all of this is simply that the “params” keyword is a “tool in the toolbox”. It’s not appropriate to use very often, but when you need it – it’s just the right tool for the job. Again, you shouldn’t abuse or misuse this to shortcut writing good code – it simply serves this purpose to make an interface easier to work with.

Posted in Best-practices, Uncategorized

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

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 2 other followers

%d bloggers like this: