9

Possible Duplicate:
Why does params behave like this?

If you write a method like this:

void TestMethod(params object[] args) { }

then if you call it like this: TestMethod() then the array will be empty.

and if you call it like this: TestMethod(null, null) then the array will be an array with two null values.

but why, when you call the method like this: TestMethod(null) will the array be null?

I would have expected the result to be an array with one null value.

I know about this C# - Is it possible to have null params? but does not explain why.

--Edit:

It's also interesting that TestMethod((object)null) is an array with one null value and TestMetod((object[])null) is a null array.

It's just a case where being explicit in your intentions, by casting null to your expected type is the right way to go.

Community
  • 1
  • 1
Hoffmania
  • 926
  • 2
  • 7
  • 15
  • 2
    That is kind of interesting, given [msdn](http://msdn.microsoft.com/en-us/library/w5zay9db.aspx) states that a single argument should be the first element in the params array. one would expect `(params) = object[]{ null }` not `(params) = null`. – Brad Christie Aug 29 '11 at 02:30
  • 4
    Maybe this is the answer? http://stackoverflow.com/questions/2210519/why-does-params-behave-like-this – Daniel T. Aug 29 '11 at 02:33
  • There's a difference between whether a reference IS null (e.g. "TestMethod (null)"), whether the object being referred to CONTAINS nulls or whether the object is merely "empty". Here's a good link on "parameter arrays": http://msdn.microsoft.com/en-us/library/aa645765%28v=vs.71%29.aspx And yes, it is possible for a function to pass "null" as a parameter. – paulsm4 Aug 29 '11 at 02:35
  • @Daniel T, that's a good link, and is the correct answer in my opinion.' – Hoffmania Aug 29 '11 at 02:41

0 Answers0