Language Features: Variable Arguments
In a recent project I decided to use variable arguments to a function - the first time I've needed to. If you haven't worked with them before, you probably don't know the point of them. They're easy to use though.
Every so often you may need to pass a number of arguments to a function, but it may be hard to predict how many. An example is the String.Format() method:
String.Format("{0:d} - {1} ({2})", DateTime.Now, msg, severity);
You could pass more or less arguments depending on what you are formatting. If you've ever given it a thought, though, you'd realize it's not obvious how to do it. You could overload the method:
String.Format(string, string); String.Format(string, string, string); String.Format(string, string, string, string);
I'm sure you can see that this would get out of hand quickly! Fortunately there's a better way though: Variable Arguments. Instead of creating overloads with more and more parameters, you can just use the params keyword. How it works is simple. Just use the params keyword, specify the datatype and variable name, and you'll actually get an array of values passed to the method. From our Format example, we would just declare it as:
String.Format(string formatString, params string[] args);
In the method itself then, you could reference the required argument formatString as any other argument, then the args array would have zero of more elements depending on how many were passed in. Just in case it's at all confusing, it's the params keyword that creates the magic. Any parameters before that one are completely normal. You could just as easily have something like this:
MyClass.MyMethod(string source, int code, params object[] values);
Important points:
- You can only have one params arguments (all others will be normal arguments)
- The argument with variable arguments must be the last (too confusing otherwise)
- You can use any datatype, but it must be declared as an array (and therefore, all variable arguments are the same type)
- In the method itself, just access the last argument as any other array (foreach works nicely)