Editorials

Using params in a C# Method

Here’s a little C# technique that can save you time when you passing an undefined set of data from one method to another. This may be a newbee kind of thing. But, if you haven’t come across it yet, it can be very handy. Let me start out with an example problem. Have you ever used the string.Format method in Dot Net? This works in VB.Net or C#. Basically, you pass in a string with placeholders to be replaced by a list of values.

string.Format(“This is a {0} message with {1} meaning”, “long”, “no”);

When the string.Format method is called as defined above, it takes the first value after the format string and replaces {0} with the text. The second value replaces {1} with it’s text. The final result is “This is a long message with no meaning”.

What is interesting is that you could call the same method passing in different data types and it still works.

string.Format(“This is a {0} word message with {1} meaning”, 9, “no”);

The reason this works is because the inputs are of type object. So, since they are an array of objects, why didn’t I have to cast them as objects? That is because of a technique where you can pass a collection of parameters to a method without having to cast them, all parameters are passed as objects instead of the original data type.

myMethod(string message, params object[] parameters)

You can have only one params collection in a method, and it must be the last parameter for the method. You can call it without specifying any parameters resulting in an empty collection, or you can pass any number of parameters, even if they are of different types.

I like using parameters for message logging by expanding on the log command to include a string and parameters that may be populated or not.

public void LogDebugMessage(message, params object[] parameters)

{

if (mylogger.debug) mylogger.LogDebug(string.format(message, parameters);

}

Now let’s say I caught an exception (ex) and want to log a debug message. I can call my logger passing values from the exception like the following:

mylogger.LogDebug(
“An exception was caught doing somethingrnMessage: {0}rnStack Trace:rn{1} ”,
ex.Messag, ex.StackTrace);

I can also use my logger without parameters:

mylogger.LogDebug(“This is a message I just have to log”);

I don’t see params used a lot. But they can be handy for certain kinds of situations. Just be aware that it only passes objects. So, if you have to box those objects a lot, it may not be the best solution.

If you want to look into it further you can find documentation at http://msdn.microsoft.com/en-us/library/w5zay9db.aspx.

Cheers,

Ben