Unknown C# keywords: params

Often overlooked, and (some may say) unloved, is the params keyword, but it’s an awesome keyword, and one you should definitely check out.

What does it do?

Well, it lets you specify a single parameter that can have a variable number of arguments.

You what?

Best shown with an example, let’s say we write an add method:

public int Add(int first, int second) { return first + second; }

meh, it’s alright, does what it says on the tin, but it’s not exactly awe-inspiring…

Oh noes! You need to add 3 things together???

public int Add(int first, int second, int third) { return first + second + third; }

oh yes, you code master you! Overloading a-plenty!

Now a fourth…

Ok, this is starting to get a bit ridiculous, if only there was some way…

public int Add(int first, int second, params int[] others) { return first + second + others.Sum(); }

So now I can call this with any number of int arguments? – well, any number > 2..?

Yes!

int ret = Add(1, 2, 3);

Is as valid as:

int ret = Add(1, 2, 3, 4);

Of course you probably won’t really need to ever do that method, so what could you use it for? How about adding strings together? What about a logging method?

We all know ToString can be an expensive method to call, it might traverse every node on a class hierarchy, or may just be the name of the type… either way, we don’t really want to call it if we can avoid it, so how about a logging method like so:

public void Log(LogLevel level, params object[] objs) { if(LoggingLevel < level) return;

StringBuilder output = new StringBuilder();
foreach(var obj in objs)
    output.Append((obj == null) ? "null" : obj.ToString());

return output;

}

Now we only call ‘ToString’ when we want to, and because we’re passing in just objects we don’t have to call ToString if the Logging Level isn’t what we want…

Of course, there are a multitude of things to use params for…

This article is part of the GWB Archives. Original Author: Chris Skardon

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.