Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Is it possible to have null params?

public void Foo(params string[] values) { } 

Is it possible that values can ever be null, or will it always be set with 0 or more items?

like image 809
michael Avatar asked Jul 05 '11 14:07

michael


2 Answers

Absolutely - you can call it with an argument of type string[] with a value of null:

string[] array = null; Foo(array); 
like image 57
Jon Skeet Avatar answered Oct 18 '22 16:10

Jon Skeet


I decided to write some code up to test this for myself. Using the following program:

using System;  namespace TestParams {     class Program     {         static void TestParamsStrings(params string[] strings)         {             if(strings == null)             {                 Console.WriteLine("strings is null.");             }             else             {                 Console.WriteLine("strings is not null.");             }         }          static void TestParamsInts(params int[] ints)         {             if (ints == null)             {                 Console.WriteLine("ints is null.");             }             else             {                 Console.WriteLine("ints is not null.");             }          }          static void Main(string[] args)         {             string[] stringArray = null;              TestParamsStrings(stringArray);             TestParamsStrings();             TestParamsStrings(null);             TestParamsStrings(null, null);              Console.WriteLine("-------");              int[] intArray = null;              TestParamsInts(intArray);             TestParamsInts();             TestParamsInts(null);             //TestParamsInts(null, null); -- Does not compile.         }     } } 

The following results are yielded:

strings is null. strings is not null. strings is null. strings is not null. ------- ints is null. ints is not null. ints is null. 

So yes, it is entirely possible for the array associated with params to be null.

like image 34
Joshua Rodgers Avatar answered Oct 18 '22 16:10

Joshua Rodgers