I have a method that uses the params keyword, like so:
private void ParamsMethod(params string[] args)
{
// Etc...
}
Then, I call the method using various combinations of arguments:
// Within the method, args is...
ParamsMethod(); // - a string array with no elements
ParamsMethod(null); // - null (Why is this?)
ParamsMethod((string)null); // - a string array with one element: null
ParamsMethod(null, null); // - a string array with two elements: null and null
ParamsMethod("s1"); // - a string array with one element: "s1"
ParamsMethod("s1", "s2"); // - a string array with two elements: "s1" and "s2"
I understand all of the cases, except for the second one. Can someone explain why ParamsMethod(null) causes args to be null, instead of an array with one null element?
A
paramsparameter is only meant to provide a convenient way of specifying values – you can still pass an array reference directly.Now,
nullis convertible to eitherstring[]orstring, so both interpretations are valid – it’s up to the spec which is preferred. The spec states in section 10.6.1.4 that:In other words, the compiler checks to see whether the argument is valid as the “normal” parameter type first, and only builds an array if it absolutely has to.