If I have a method that takes params as input. Do I need to check for null on that set of params ? Well answer is yes if you want to be really sure because there is one way to get a null into the method call.
Note: I am currently working on code that I promised the Tech Ed Berlin audience when I delivered my talk Flexible Design last week. If anyone waiting is reading this – it’s on the way. I just want to make sure i document the sample so that the code may be read from start to finish and that the message is clear enough.
Below is a test class with one test: TestsOnCallingAMethodThatTakesParams(). The test, which is not so much a test as it is an easy way to execute a bit of code for investigative purposes, makes calls to a method that is defined as a params input: TestACallWithParams(params string[] args).
I hadn’t really thought about this before but when I saw a method null checking to see if the “args” parameter was null it got me thinking. Under what conditions could args in this method signature actually be null?
The code below is pretty self explanatory but just to be sure; IF you decide to call a method specifying params for a parameter and you call the method with a null value TestACallWithParams(null) then the parameter value of the args parameter will indeed be null.
Personally I feel that calling a method that defines params with an actual null value is an error on the programmers part. The correct way to call this method is to leave out the parameters altogether TestACallWithParams(). This causes the input to be an empty array which you can use in a foreach statement or what ever you like.
[TestClass]
public class tests
{
[TestMethod]
public void TestsOnCallingAMethodThatTakesParams()
{
TestACallWithParams();
TestACallWithParams(null);
TestACallWithParams((string)null);
string s = null;
TestACallWithParams(s);
TestACallWithParams(new string[] { });
TestACallWithParams(null, null);
TestACallWithParams("foo", "bar");
TestACallWithParams(new [] { "foo", "bar" } );
}
public void TestACallWithParams(params string[] args)
{
if (args == null)
{
// Do I really need to check for null here?
}
/*
If you break here and look in the immediate window
these are the results from each call above:
args
{string[0]}
args
null <- NOTE: The null value here in the call with nust null!
args
{string[0]}
[0]: null
args
{string[1]}
[0]: null
args
{string[0]}
args
{string[2]}
[0]: null
[1]: null
args
{string[2]}
[0]: "foo"
[1]: "bar"
args
{string[2]}
[0]: "foo"
[1]: "bar"
*/
}
}
In conclusion
You should not have to check for null on a parameter marked as being params. However if you want to be 100% certain that the user of this method does not make a coding mistake you have to check it.
Cheers,
M.
posted @ Friday, November 20, 2009 12:01 PM