Unknown C# keywords: params
Posted
by Chris Skardon
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Chris Skardon
Published on Tue, 01 Feb 2011 15:47:11 GMT
Indexed on
2011/02/01
23:26 UTC
Read the original article
Hit count: 292
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…
© Geeks with Blogs or respective owner